GHC issueshttps://gitlab.haskell.org/ghc/ghc//issues20190801T08:54:16Zhttps://gitlab.haskell.org/ghc/ghc//issues/16967More of Note [Letbound skolems]20190801T08:54:16ZRichard Eisenbergrae@richarde.devMore of Note [Letbound skolems]Note `[Letbound skolems]` in TcSMonad says
```
If * the inert set contains a canonical Given CTyEqCan (a ~ ty)
and * 'a' is a skolem bound in this very implication,
then:
a) The Given is pretty much a letbinding,
...
```
and we can float equalities past these letbound skolems.
With that in mind, consider this, pulled from https://gitlab.haskell.org/ghc/ghc/issues/9223#note_92675:
```hs
data Token t = forall a. Token (SomeToken t a)
data SomeToken t a = SomeToken (t a) a
data TokenType a where
TokLitInt :: TokenType Integer
TokLitPlus :: TokenType ()
 Without the type signature, GHC 7.8.3 can't infer the type of this function.
foo :: Token TokenType > Integer
foo (Token (SomeToken TokLitInt x)) = x + 1
foo _ = 0
```
Here is, roughly, what happens (uniques from actual trace left in for verisimilitude):
1. Guess `foo :: alpha_aUv[1] > beta_aUt[1]`
2. Figure out `alpha_aUv[1] := Token gamma_aUw[1]`
3. bump level by bringing `a_aUx[2]` into scope {
4. emit `co1_aUz :: gamma_aUw[1] ~ TokenType` and set `delta_aUy[2] := a_aUx[2]`
5. bump level by bringing `a_aUx[2] ~ Integer` into scope as a Given {
6. bind `x :: a_aUx[2]`
7. infer RHS has type `a_aUx[2]`
8. emit `co2_aUR :: beta_aUt[1] ~ a_aUx[2]`
9. } package implication: `forall[3]. a_aUx[2] ~ Integer ==> beta_aUt[1] ~ a_aUx[2]`
10. } package implication
```
forall a_aUx[2]. () ==> co1_aUz :: gamma_aUw[1] ~ TokenType
forall[3] . a_aUx[2] ~ Integer ==> co2_aUR :: beta_aUt[1] ~ a_aUx[2]
```
11. Run simplifier, yielding `gamma_aUw[1] := TokenType` (after some floating) and leading to residual
```
forall a_aUx[2]. () ==> forall[3] . a_aUx[2] ~ Integer ==> co2_aUR :: beta_aUt[1] ~ Integer
```
At this point, GHC gives up and issues an error. But actually, we can do better. If we merge the two implications (which seems allowable because there is no metavariable at level `2` that might be able to observe the difference between the original nested implication and a merged implication), then `a_aUx[2]` becomes a letbound skolem and thus cannot block floating. I don't really think we should merge implications though  I don't know all the implications of doing so (pun irrelevant). Instead, we can just expand the check in `Note [Letbound skolems]`. Here is the full specification in that Note:
```
Note [Letbound skolems]
~~~~~~~~~~~~~~~~~~~~~~~~
If * the inert set contains a canonical Given CTyEqCan (a ~ ty)
and * 'a' is a skolem bound in this very implication,
then:
a) The Given is pretty much a letbinding, like
f :: (a ~ b>c) => a > a
Here the equality constraint is like saying
let a = b>c in ...
It is not adding any new, local equality information,
and hence can be ignored by has_given_eqs
```
I propose changing to
```
Note [Letbound skolems]
~~~~~~~~~~~~~~~~~~~~~~~~
If * the inert set contains a canonical Given CTyEqCan (a ~ ty)
and * 'a' is a skolem bound in an implication at TcLevel N,
and * we are examining a constraint whose maximum level is M,
and * M < N
then:
a) The Given behaves as a letbinding, like
f :: (a ~ b>c) => a > a
Here the equality constraint is like saying
let a = b>c in ...
Given that the constraint in question cannot observe the difference between
the skolem's binding site and its equality constraint (because no variable
inhabits a level in between those points), it is not adding any new, local equality
information, and hence can be ignored by has_given_eqs
```
There is a point (b) to this Note that, I think, does not generalize in the same way, and so I have left it out here. (Obviously, some rejiggering will be required in the actual Note and the implementation of these ideas.)
What do we think? Can we float in this way? The implementation should be easy  it's the specification we must be careful about.Note `[Letbound skolems]` in TcSMonad says
```
If * the inert set contains a canonical Given CTyEqCan (a ~ ty)
and * 'a' is a skolem bound in this very implication,
then:
a) The Given is pretty much a letbinding,
...
```
and we can float equalities past these letbound skolems.
With that in mind, consider this, pulled from https://gitlab.haskell.org/ghc/ghc/issues/9223#note_92675:
```hs
data Token t = forall a. Token (SomeToken t a)
data SomeToken t a = SomeToken (t a) a
data TokenType a where
TokLitInt :: TokenType Integer
TokLitPlus :: TokenType ()
 Without the type signature, GHC 7.8.3 can't infer the type of this function.
foo :: Token TokenType > Integer
foo (Token (SomeToken TokLitInt x)) = x + 1
foo _ = 0
```
Here is, roughly, what happens (uniques from actual trace left in for verisimilitude):
1. Guess `foo :: alpha_aUv[1] > beta_aUt[1]`
2. Figure out `alpha_aUv[1] := Token gamma_aUw[1]`
3. bump level by bringing `a_aUx[2]` into scope {
4. emit `co1_aUz :: gamma_aUw[1] ~ TokenType` and set `delta_aUy[2] := a_aUx[2]`
5. bump level by bringing `a_aUx[2] ~ Integer` into scope as a Given {
6. bind `x :: a_aUx[2]`
7. infer RHS has type `a_aUx[2]`
8. emit `co2_aUR :: beta_aUt[1] ~ a_aUx[2]`
9. } package implication: `forall[3]. a_aUx[2] ~ Integer ==> beta_aUt[1] ~ a_aUx[2]`
10. } package implication
```
forall a_aUx[2]. () ==> co1_aUz :: gamma_aUw[1] ~ TokenType
forall[3] . a_aUx[2] ~ Integer ==> co2_aUR :: beta_aUt[1] ~ a_aUx[2]
```
11. Run simplifier, yielding `gamma_aUw[1] := TokenType` (after some floating) and leading to residual
```
forall a_aUx[2]. () ==> forall[3] . a_aUx[2] ~ Integer ==> co2_aUR :: beta_aUt[1] ~ Integer
```
At this point, GHC gives up and issues an error. But actually, we can do better. If we merge the two implications (which seems allowable because there is no metavariable at level `2` that might be able to observe the difference between the original nested implication and a merged implication), then `a_aUx[2]` becomes a letbound skolem and thus cannot block floating. I don't really think we should merge implications though  I don't know all the implications of doing so (pun irrelevant). Instead, we can just expand the check in `Note [Letbound skolems]`. Here is the full specification in that Note:
```
Note [Letbound skolems]
~~~~~~~~~~~~~~~~~~~~~~~~
If * the inert set contains a canonical Given CTyEqCan (a ~ ty)
and * 'a' is a skolem bound in this very implication,
then:
a) The Given is pretty much a letbinding, like
f :: (a ~ b>c) => a > a
Here the equality constraint is like saying
let a = b>c in ...
It is not adding any new, local equality information,
and hence can be ignored by has_given_eqs
```
I propose changing to
```
Note [Letbound skolems]
~~~~~~~~~~~~~~~~~~~~~~~~
If * the inert set contains a canonical Given CTyEqCan (a ~ ty)
and * 'a' is a skolem bound in an implication at TcLevel N,
and * we are examining a constraint whose maximum level is M,
and * M < N
then:
a) The Given behaves as a letbinding, like
f :: (a ~ b>c) => a > a
Here the equality constraint is like saying
let a = b>c in ...
Given that the constraint in question cannot observe the difference between
the skolem's binding site and its equality constraint (because no variable
inhabits a level in between those points), it is not adding any new, local equality
information, and hence can be ignored by has_given_eqs
```
There is a point (b) to this Note that, I think, does not generalize in the same way, and so I have left it out here. (Obviously, some rejiggering will be required in the actual Note and the implementation of these ideas.)
What do we think? Can we float in this way? The implementation should be easy  it's the specification we must be careful about.https://gitlab.haskell.org/ghc/ghc//issues/16982Break out TcTyVar into its own type20190801T08:53:00ZRichard Eisenbergrae@richarde.devBreak out TcTyVar into its own typeRight now, the type `Var` has three constructors: `Id`, `TyVar`, and `TcTyVar`. The last of these should never occur in a Core program, but exists only in the typechecker. This ticket is a refactoring that moves `TcTyVar` outside of `Var` and into its own type.
Here is a rough sketch of the proposed future (all modulo field renaming where necessary to avoid duplicates):
```hs
data Var
= Id {# UNPACK #} !Id
 TyVar {# UNPACK #} !TyVar
data Id = MkId ...  stuff that's in today's Id constructor
data TyVar = MkTyVar ...  stuff that's in today's TyVar constructor
data MetaTyVar = MkMeta ...  stuff that's in today's MetaTv constructor of TcTyVarDetails, plus a Name and Type
data SkolemTyVar = MkSkol ...  stuff that's in today's SkolemTv constructor of TcTyVarDetails, plus a Name and Type
data RuntimeUnkTyVar = MkRtUnk Name Type  NB: today's RuntimeUnk constructor of TcTyVarDetails carries no data
data TcTyVar
= SkolemTv {# UNPACK #} !SkolemTyVar
 MetaTv {# UNPACK #} !MetaTyVar
 RuntimeUnk {# UNPACK #} !RuntimeUnkTyVar
data TcCoVar = TcCoVar ...  evolved from today's CoercionHole
data Type = ...  TcTyVarTy TcTyVar  new constructor in Type
data Coercion = ...  TcCoVarCo TcCoVar  new constructor in Coercion, replacing HoleCo
data TcOrCoreVar
= TcTyVar !TcTyVar  can't unpack a sum
 TcCoVar {# UNPACK #} !TcCoVar
 Var !Var  can't unpack a sum
```
The observation that leads to this is that we rarely want to mix `TcTyVar`s with other `TyVar`s. So I think `TcOrCoreVar` will have few uses. In particular, when we collect free variables, we often know, in advance, whether we want `Tc` vars or Core vars. This will require new functions that walk over types/coercions collecting variables, but I think that's acceptable. Also, note the addition of `TyVar` and `Id` types (unpacked into `Var`), allowing us to keep these separate and statically checked. Naturally, spotting `TcTyVarTy` or `TcCoVarCo` in Lint will be an error.
There is no pressing need for this refactor, but I think it will smoke out some bugs and be cleaner going forward.Right now, the type `Var` has three constructors: `Id`, `TyVar`, and `TcTyVar`. The last of these should never occur in a Core program, but exists only in the typechecker. This ticket is a refactoring that moves `TcTyVar` outside of `Var` and into its own type.
Here is a rough sketch of the proposed future (all modulo field renaming where necessary to avoid duplicates):
```hs
data Var
= Id {# UNPACK #} !Id
 TyVar {# UNPACK #} !TyVar
data Id = MkId ...  stuff that's in today's Id constructor
data TyVar = MkTyVar ...  stuff that's in today's TyVar constructor
data MetaTyVar = MkMeta ...  stuff that's in today's MetaTv constructor of TcTyVarDetails, plus a Name and Type
data SkolemTyVar = MkSkol ...  stuff that's in today's SkolemTv constructor of TcTyVarDetails, plus a Name and Type
data RuntimeUnkTyVar = MkRtUnk Name Type  NB: today's RuntimeUnk constructor of TcTyVarDetails carries no data
data TcTyVar
= SkolemTv {# UNPACK #} !SkolemTyVar
 MetaTv {# UNPACK #} !MetaTyVar
 RuntimeUnk {# UNPACK #} !RuntimeUnkTyVar
data TcCoVar = TcCoVar ...  evolved from today's CoercionHole
data Type = ...  TcTyVarTy TcTyVar  new constructor in Type
data Coercion = ...  TcCoVarCo TcCoVar  new constructor in Coercion, replacing HoleCo
data TcOrCoreVar
= TcTyVar !TcTyVar  can't unpack a sum
 TcCoVar {# UNPACK #} !TcCoVar
 Var !Var  can't unpack a sum
```
The observation that leads to this is that we rarely want to mix `TcTyVar`s with other `TyVar`s. So I think `TcOrCoreVar` will have few uses. In particular, when we collect free variables, we often know, in advance, whether we want `Tc` vars or Core vars. This will require new functions that walk over types/coercions collecting variables, but I think that's acceptable. Also, note the addition of `TyVar` and `Id` types (unpacked into `Var`), allowing us to keep these separate and statically checked. Naturally, spotting `TcTyVarTy` or `TcCoVarCo` in Lint will be an error.
There is no pressing need for this refactor, but I think it will smoke out some bugs and be cleaner going forward.https://gitlab.haskell.org/ghc/ghc//issues/17032Refactor TcTyCon into its own type20190819T21:55:35ZRichard Eisenbergrae@richarde.devRefactor TcTyCon into its own type`TcTyCon` is currently a constructor of `TyCon`. However, there are a number of places during type inference where we know statically that a `TyCon` should always be a `TcTyCon`. Indeed we have a type synonym `type TcTyCon = TyCon` for this purpose.
I think it would be better to move `TcTyCon` out to its own type and then embed that in `TyCon` as necessary. (If we ever split `TcType` from `Type`, we *won't* embed in `TyCon`.) This gives better static guarantees. With an `{# UNPACK #}`, I don't think there is any loss, at all.`TcTyCon` is currently a constructor of `TyCon`. However, there are a number of places during type inference where we know statically that a `TyCon` should always be a `TcTyCon`. Indeed we have a type synonym `type TcTyCon = TyCon` for this purpose.
I think it would be better to move `TcTyCon` out to its own type and then embed that in `TyCon` as necessary. (If we ever split `TcType` from `Type`, we *won't* embed in `TyCon`.) This gives better static guarantees. With an `{# UNPACK #}`, I don't think there is any loss, at all.Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/17033Investigate Note [Kind checking recursive type and class declarations]20200123T19:42:31ZRichard Eisenbergrae@richarde.devInvestigate Note [Kind checking recursive type and class declarations]`Note [Kind checking recursive type and class declarations]` in TcTyClsDecls describes adding the tycons of a mutually recursive group both to the global env't and the local env't during kind checking.
1. Is this true?
2. If it is true, do we need to do it?
I conjecture that the answer to one of these questions is "no". If so, I will fix. This likely changed at some point with heavier reliance on `TcTyCon`s.`Note [Kind checking recursive type and class declarations]` in TcTyClsDecls describes adding the tycons of a mutually recursive group both to the global env't and the local env't during kind checking.
1. Is this true?
2. If it is true, do we need to do it?
I conjecture that the answer to one of these questions is "no". If so, I will fix. This likely changed at some point with heavier reliance on `TcTyCon`s.Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/17053`Wredundantconstraints` depends on the ordering of constraints with overlap...20200123T19:42:31ZInThisStyle10s6p`Wredundantconstraints` depends on the ordering of constraints with overlapping superclasses## Summary
The `Wredundantconstraints` flag does not result in a warning when it should, due to the ordering of constraints.
## Steps to reproduce
In the following code
```haskell
{# OPTIONS_GHC Wredundantconstraints #}
{# OPTIONS_GHC Werror #}
module Test where
class A a where
a :: a > a
class A a => B a where
b :: a
class A a => C a where
noWarning :: (C a, B a) => a
noWarning = a b
warning :: (B a, C a) => a
warning = a b
```
I get only the error
```
Test.hs:17:1: error: [Wredundantconstraints, Werror=redundantconstraints]
• Redundant constraint: C a
• In the type signature for:
warning :: forall a. (B a, C a) => a

17  warning :: (B a, C a) => a
 ^^^^^^^^^^^^^^^^^^^^^^^^^^
```
## Expected behavior
There should be two errors, one for `warning` and one for `noWarning`. This would be in line with the behaviour of GHC with the constraints `(Eq a, Ord a)` and `(Ord a, Eq a)`, both of which result in warnings in similar situations.
## Environment
* GHC version used: 8.6.5## Summary
The `Wredundantconstraints` flag does not result in a warning when it should, due to the ordering of constraints.
## Steps to reproduce
In the following code
```haskell
{# OPTIONS_GHC Wredundantconstraints #}
{# OPTIONS_GHC Werror #}
module Test where
class A a where
a :: a > a
class A a => B a where
b :: a
class A a => C a where
noWarning :: (C a, B a) => a
noWarning = a b
warning :: (B a, C a) => a
warning = a b
```
I get only the error
```
Test.hs:17:1: error: [Wredundantconstraints, Werror=redundantconstraints]
• Redundant constraint: C a
• In the type signature for:
warning :: forall a. (B a, C a) => a

17  warning :: (B a, C a) => a
 ^^^^^^^^^^^^^^^^^^^^^^^^^^
```
## Expected behavior
There should be two errors, one for `warning` and one for `noWarning`. This would be in line with the behaviour of GHC with the constraints `(Eq a, Ord a)` and `(Ord a, Eq a)`, both of which result in warnings in similar situations.
## Environment
* GHC version used: 8.6.5https://gitlab.haskell.org/ghc/ghc//issues/17072Dependent quantification prevents unification20200123T19:42:31ZVladislav ZavialovDependent quantification prevents unification## Summary
Replacing `k > Type` with `forall (a :: k) > Type` in a kind of a type constructor should not have any effect. The latter gives a name to the variable, but is otherwise equivalent... or so I thought.
Consider these definitions:
```
data B1 :: k > Type
type family F1 :: k > Type where
F1 = B1
```
GHC happily accepts them, unifying the kinds of `B1` and `F1`. However, if I make use of dependent quantification in `B` but not in `F`:
```
data B2 :: forall (a :: k) > Type
type family F2 :: k > Type where
F2 = B2
```
... GHC gets confused:
```
• Expected kind ‘k1 > Type’,
but ‘B2’ has kind ‘forall (a :: k0) > Type’
• In the type ‘B2’
In the type family declaration for ‘F2’

14  F2 = B2
 ^^
```
## Steps to reproduce
Load this in GHCi:
```
{# LANGUAGE PolyKinds, TypeFamilies, RankNTypes #}
module T where
import Data.Kind (Type)
data B1 :: k > Type
type family F1 :: k > Type where
F1 = B1
data B2 :: forall (a :: k) > Type
type family F2 :: k > Type where
F2 = B2
```
## Expected behavior
Both `F1` and `F2` should be accepted.
## Environment
* GHC version used: HEAD## Summary
Replacing `k > Type` with `forall (a :: k) > Type` in a kind of a type constructor should not have any effect. The latter gives a name to the variable, but is otherwise equivalent... or so I thought.
Consider these definitions:
```
data B1 :: k > Type
type family F1 :: k > Type where
F1 = B1
```
GHC happily accepts them, unifying the kinds of `B1` and `F1`. However, if I make use of dependent quantification in `B` but not in `F`:
```
data B2 :: forall (a :: k) > Type
type family F2 :: k > Type where
F2 = B2
```
... GHC gets confused:
```
• Expected kind ‘k1 > Type’,
but ‘B2’ has kind ‘forall (a :: k0) > Type’
• In the type ‘B2’
In the type family declaration for ‘F2’

14  F2 = B2
 ^^
```
## Steps to reproduce
Load this in GHCi:
```
{# LANGUAGE PolyKinds, TypeFamilies, RankNTypes #}
module T where
import Data.Kind (Type)
data B1 :: k > Type
type family F1 :: k > Type where
F1 = B1
data B2 :: forall (a :: k) > Type
type family F2 :: k > Type where
F2 = B2
```
## Expected behavior
Both `F1` and `F2` should be accepted.
## Environment
* GHC version used: HEADVladislav ZavialovVladislav Zavialovhttps://gitlab.haskell.org/ghc/ghc//issues/17130Lift restriction that pattern matching on existentials must be strict20200123T19:43:03ZbfrkLift restriction that pattern matching on existentials must be strict## Motivation
https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#restrictions says:
> You can’t patternmatch on an existentially quantified constructor in a let or where group of bindings.
and later on
> In general, you can only patternmatch on an existentiallyquantified constructor in a case expression or in the patterns of a function definition. The reason for this restriction is really an implementation one. Typechecking binding groups is already a nightmare without existentials complicating the picture. Also an existential pattern binding at the top level of a module doesn’t make sense, because it’s not clear how to prevent the existentiallyquantified type “escaping”. So for now, there’s a simpletostate restriction. We’ll see how annoying it is.
I am here to tell you that I find it very much annoying.
In Darcs it forces us to use nested cases (with increasing indentation depth, bad). If we happen to be in a `do` block, which is often the case, we can resort to
```
do
Sealed xs < read some patches
Sealed qs < read more patches
...
```
Here, I am using, as an example, an existential defined as
```
data Sealed a where
Sealed :: a wX > Sealed a
```
where the type variable `wX` is a phantom type that symbolically stands for the range of the partial bijection represented by a patch.
This style is acceptable, though sometimes I would like to extract a piece of code and factor it into a local function and this doesn't work because of the let restriction. I usually find a workaround but it can be a hassle.
Anyway, lately I came across something that I *really* don't like. We use `unsafeInterleaveIO` when reading hashed files from disk; this is okay because the file name determines the content, so these are essentially writeonce, so nothing bad can happen. In order to preserve laziness I would like to say
```
do
~(Sealed xs) < unsafeInterleaveIO $ read some patches
~(Sealed qs) < unsafeInterleaveIO $ read more patches
...
```
and now GHC (8.6.5) tells me that I cannot do that. Without the laziness annotation, the pattern match on the Sealed constructor forces evaluation until we know at least that we have an actual Sealed, not bottom. And that may mean we must read a file, which we don't want to do, for efficiency, since it may not be needed at all. That's what the `unsafeInterleaveIO` is for.
The only way to achieve laziness here is to use an unsafe coercion on the wX phantom type that allows us to pull out the existentially quantified content of a Sealed, then unconditionally reseal it:
```
unsafeUnseal :: Sealed a > a wX
unsafeUnseal (Sealed a) = unsafeCoerce a
...
do
Sealed xs < Sealed $ unsafeUnseal $ unsafeInterleaveIO $ read some patches
Sealed qs < Sealed $ unsafeUnseal $ unsafeInterleaveIO $ read more patches
...
```
This is quite an ugly hack.
## Proposal
I don't have a ready made proposal but I think you get the gist. Lift the above cited restriction, at least allow to use matching on an existentials inside a lazy pattern.
Cheers
Ben## Motivation
https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#restrictions says:
> You can’t patternmatch on an existentially quantified constructor in a let or where group of bindings.
and later on
> In general, you can only patternmatch on an existentiallyquantified constructor in a case expression or in the patterns of a function definition. The reason for this restriction is really an implementation one. Typechecking binding groups is already a nightmare without existentials complicating the picture. Also an existential pattern binding at the top level of a module doesn’t make sense, because it’s not clear how to prevent the existentiallyquantified type “escaping”. So for now, there’s a simpletostate restriction. We’ll see how annoying it is.
I am here to tell you that I find it very much annoying.
In Darcs it forces us to use nested cases (with increasing indentation depth, bad). If we happen to be in a `do` block, which is often the case, we can resort to
```
do
Sealed xs < read some patches
Sealed qs < read more patches
...
```
Here, I am using, as an example, an existential defined as
```
data Sealed a where
Sealed :: a wX > Sealed a
```
where the type variable `wX` is a phantom type that symbolically stands for the range of the partial bijection represented by a patch.
This style is acceptable, though sometimes I would like to extract a piece of code and factor it into a local function and this doesn't work because of the let restriction. I usually find a workaround but it can be a hassle.
Anyway, lately I came across something that I *really* don't like. We use `unsafeInterleaveIO` when reading hashed files from disk; this is okay because the file name determines the content, so these are essentially writeonce, so nothing bad can happen. In order to preserve laziness I would like to say
```
do
~(Sealed xs) < unsafeInterleaveIO $ read some patches
~(Sealed qs) < unsafeInterleaveIO $ read more patches
...
```
and now GHC (8.6.5) tells me that I cannot do that. Without the laziness annotation, the pattern match on the Sealed constructor forces evaluation until we know at least that we have an actual Sealed, not bottom. And that may mean we must read a file, which we don't want to do, for efficiency, since it may not be needed at all. That's what the `unsafeInterleaveIO` is for.
The only way to achieve laziness here is to use an unsafe coercion on the wX phantom type that allows us to pull out the existentially quantified content of a Sealed, then unconditionally reseal it:
```
unsafeUnseal :: Sealed a > a wX
unsafeUnseal (Sealed a) = unsafeCoerce a
...
do
Sealed xs < Sealed $ unsafeUnseal $ unsafeInterleaveIO $ read some patches
Sealed qs < Sealed $ unsafeUnseal $ unsafeInterleaveIO $ read more patches
...
```
This is quite an ugly hack.
## Proposal
I don't have a ready made proposal but I think you get the gist. Lift the above cited restriction, at least allow to use matching on an existentials inside a lazy pattern.
Cheers
Benhttps://gitlab.haskell.org/ghc/ghc//issues/17167Role annotations on classes require modulewide IncoherentInstances20200123T19:43:04ZAdam GundryRole annotations on classes require modulewide IncoherentInstancesPer #8773, specifying a nonnominal role for a class parameter requires `IncoherentInstances`:
```hs
{# LANGUAGE RoleAnnotations #}
{# LANGUAGE IncoherentInstances #}
class C c
type role C phantom
```
For instances, the `IncoherentInstances` modulewide `LANGUAGE` pragma has been deprecated in favour of perinstance `{# INCOHERENT #}` pragmas. However, there doesn't appear to be an equivalent for `type role` on classes. This is awkward because I do not want the instances of `C` to be marked as incoherent, and hence they cannot be defined in the same module as `C`.
I think it would make sense to be able to use `{# INCOHERENT #}` after `type role`, so that it would be accepted without modulewide `IncoherentInstances`.Per #8773, specifying a nonnominal role for a class parameter requires `IncoherentInstances`:
```hs
{# LANGUAGE RoleAnnotations #}
{# LANGUAGE IncoherentInstances #}
class C c
type role C phantom
```
For instances, the `IncoherentInstances` modulewide `LANGUAGE` pragma has been deprecated in favour of perinstance `{# INCOHERENT #}` pragmas. However, there doesn't appear to be an equivalent for `type role` on classes. This is awkward because I do not want the instances of `C` to be marked as incoherent, and hence they cannot be defined in the same module as `C`.
I think it would make sense to be able to use `{# INCOHERENT #}` after `type role`, so that it would be accepted without modulewide `IncoherentInstances`.https://gitlab.haskell.org/ghc/ghc//issues/17186Another loop with injective type families20201110T15:28:13ZRichard Eisenbergrae@richarde.devAnother loop with injective type familiesBroken out from #16512, the following program causes GHC to loop:
```hs
{# LANGUAGE DataKinds #}
{# LANGUAGE FlexibleContexts #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE TypeFamilyDependencies #}
{# LANGUAGE TypeOperators, AllowAmbiguousTypes #}
module T16512 where
 This test is significantly abbreviated from what was posted; see
 #16512 for more context.
type family Dim v
type family v `OfDim` (n :: Dim v) = r  r > n
(!*^) :: Dim m `OfDim` j > Dim m `OfDim` i
(!*^) = undefined
```
The fix for #16512 does not fix this.Broken out from #16512, the following program causes GHC to loop:
```hs
{# LANGUAGE DataKinds #}
{# LANGUAGE FlexibleContexts #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE TypeFamilyDependencies #}
{# LANGUAGE TypeOperators, AllowAmbiguousTypes #}
module T16512 where
 This test is significantly abbreviated from what was posted; see
 #16512 for more context.
type family Dim v
type family v `OfDim` (n :: Dim v) = r  r > n
(!*^) :: Dim m `OfDim` j > Dim m `OfDim` i
(!*^) = undefined
```
The fix for #16512 does not fix this.Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/17201Levity polymorphism and defaulting20210714T07:51:58ZKrzysztof GogolewskiLevity polymorphism and defaultingThis ticket concerns two closely related items regarding levity polymorphism.
1. Consider
```
f1 :: forall (p :: RuntimeRep > Type) (r :: RuntimeRep). p r > p r
f1 x = x
 Inferred type g1 :: forall (p :: RuntimeRep > Type). p 'LiftedRep > p 'LiftedRep
g1 = f1
f2 :: (p :: Bool > Type) (r :: Bool). p r > p r
f2 x = x
 Inferred type g2 :: forall (p :: Bool > Type) (r :: Bool). p r > p r
g2 = f2
f3 :: forall k (p :: k > Type) (r :: k). p r > p r
f3 x = x
 Inferred type g3 :: forall k (p :: k > Type) (r :: k). p r > p r
g3 = f3
type family R
type instance R = RuntimeRep
f4 :: (p :: R> Type) (r :: R). p r > p r
f2 x = x
 Inferred type g4 :: forall (p :: R > Type) (r :: R). p r > p r
g4 = f4
```
As you can see `g1` gets a less general type than `g2`, but the only difference is `RuntimeRep` vs `Bool`.
And `g3` also gets a more general type, even though `k` could be instantiated to `RuntimeRep` in a call.
And `g4` disguises `RuntimeRep` behind a type family, and so becomes polymorphic.
This inconsistency is all pretty disgusting.
Proposed alternative:
* When we typecheck a binder, we unify the kind of its type with `TYPE q`, and emit a new constraint `StaticRuntimeRep q`. Similarly for other places where levity polymorphsm
* Never generalise over `StaticRuntimeRep` constraints.
* Default any unsolved `StaticRuntimeRep` constraints at the end.
That could even be connected the defaulting mechanism, so that you could say `default (UnliftedRep)` in a module, or `default (One)` for multiplicity polymorphism in linear types.
Richard says that a lot of machinery for `TypeLike` (#15979) will overlap with this ticket.
2. Consider
```
f x = x
g = f 0#
```
Currently, when `f` is typechecked, it's argument is inferred to be lifted, and typechecking of `g` fails. An alternative strategy is to mimic monomorphism restriction. Rather than *defaulting*
RuntimeRep varaibles in `TcMType.defaultTyVar`, simply *refrain from quantifying over it*. The type of `f` would be `forall (a :: TYPE q). a > a`, where `q` is a free unification variable.
This ticket concerns two closely related items regarding levity polymorphism.
1. Consider
```
f1 :: forall (p :: RuntimeRep > Type) (r :: RuntimeRep). p r > p r
f1 x = x
 Inferred type g1 :: forall (p :: RuntimeRep > Type). p 'LiftedRep > p 'LiftedRep
g1 = f1
f2 :: (p :: Bool > Type) (r :: Bool). p r > p r
f2 x = x
 Inferred type g2 :: forall (p :: Bool > Type) (r :: Bool). p r > p r
g2 = f2
f3 :: forall k (p :: k > Type) (r :: k). p r > p r
f3 x = x
 Inferred type g3 :: forall k (p :: k > Type) (r :: k). p r > p r
g3 = f3
type family R
type instance R = RuntimeRep
f4 :: (p :: R> Type) (r :: R). p r > p r
f2 x = x
 Inferred type g4 :: forall (p :: R > Type) (r :: R). p r > p r
g4 = f4
```
As you can see `g1` gets a less general type than `g2`, but the only difference is `RuntimeRep` vs `Bool`.
And `g3` also gets a more general type, even though `k` could be instantiated to `RuntimeRep` in a call.
And `g4` disguises `RuntimeRep` behind a type family, and so becomes polymorphic.
This inconsistency is all pretty disgusting.
Proposed alternative:
* When we typecheck a binder, we unify the kind of its type with `TYPE q`, and emit a new constraint `StaticRuntimeRep q`. Similarly for other places where levity polymorphsm
* Never generalise over `StaticRuntimeRep` constraints.
* Default any unsolved `StaticRuntimeRep` constraints at the end.
That could even be connected the defaulting mechanism, so that you could say `default (UnliftedRep)` in a module, or `default (One)` for multiplicity polymorphism in linear types.
Richard says that a lot of machinery for `TypeLike` (#15979) will overlap with this ticket.
2. Consider
```
f x = x
g = f 0#
```
Currently, when `f` is typechecked, it's argument is inferred to be lifted, and typechecking of `g` fails. An alternative strategy is to mimic monomorphism restriction. Rather than *defaulting*
RuntimeRep varaibles in `TcMType.defaultTyVar`, simply *refrain from quantifying over it*. The type of `f` would be `forall (a :: TYPE q). a > a`, where `q` is a free unification variable.
https://gitlab.haskell.org/ghc/ghc//issues/17223Slow Typechecking (Followup of #14987)20210312T23:10:14ZVictor Cacciari MiraldoSlow Typechecking (Followup of #14987)## Summary
Type Checking consumes an exponential amount of memory and is consequently very slow
in the presence of complicated pattern matching. This is a followup of #14987
The attached files have been generated with Template Haskell and are essentially
a selfcontained version of a `stack build ghcoptions="ddumpsplices ddumptofile"`
of [this repository](https://github.com/VictorCMiraldo/hdiff).
## Steps to reproduce
Compile the attached files. Might be a good idea to `ulimit m`
the shell before calling the compiler to prevent the machine from freezing.
[Gohdiff900744.hs](/uploads/7f9597aa8b49c9d360e382d8309385ce/Gohdiff900744.hs)
[Pythonhdiffe009013.hs](/uploads/42d08a992ed30ab15f905f8a0f75ca32/Pythonhdiffe009013.hs)
### Structure of Attached Files
The structure of the attached files is simple, but very long and mechanical (hence why we are
using TH!). It consists of a generic instance for mutually recursive types using the `genericsmrsop` library.
For example,
```haskell
data A = A0 Int  A1 B
data B = B0 Char  B1 A
 Now, call the TH to generate the monstrous code
deriveFamily ''Singl [t A ]
```
would yield something in the lines of
```haskell
type FamA = [ A , B ]
type CodesA = [ [ [ Int ] , [I (S Z)] ]
, [ [ Char ], [I Z] ] ]
instance Family Singl FamA CodesA where
sfrom SZ (A0 c) = Rep (Here (c :* Nil))
sfrom SZ (A1 b) = Rep (There (Here (b :* Nil))
sfrom (SS SZ) (B0 c) = Rep (Here (c :* Nil))
sfrom (SS SZ) (B1 a) = Rep (Here (There (a :* Nil))
sto ...  inverse of sfrom
```
The attached files are the versions we get from attempting to use `languagego` or `languagepython` with
`genericsmrsop`.
## Environment
* GHC version used: 8.4.2, 8.6.5## Summary
Type Checking consumes an exponential amount of memory and is consequently very slow
in the presence of complicated pattern matching. This is a followup of #14987
The attached files have been generated with Template Haskell and are essentially
a selfcontained version of a `stack build ghcoptions="ddumpsplices ddumptofile"`
of [this repository](https://github.com/VictorCMiraldo/hdiff).
## Steps to reproduce
Compile the attached files. Might be a good idea to `ulimit m`
the shell before calling the compiler to prevent the machine from freezing.
[Gohdiff900744.hs](/uploads/7f9597aa8b49c9d360e382d8309385ce/Gohdiff900744.hs)
[Pythonhdiffe009013.hs](/uploads/42d08a992ed30ab15f905f8a0f75ca32/Pythonhdiffe009013.hs)
### Structure of Attached Files
The structure of the attached files is simple, but very long and mechanical (hence why we are
using TH!). It consists of a generic instance for mutually recursive types using the `genericsmrsop` library.
For example,
```haskell
data A = A0 Int  A1 B
data B = B0 Char  B1 A
 Now, call the TH to generate the monstrous code
deriveFamily ''Singl [t A ]
```
would yield something in the lines of
```haskell
type FamA = [ A , B ]
type CodesA = [ [ [ Int ] , [I (S Z)] ]
, [ [ Char ], [I Z] ] ]
instance Family Singl FamA CodesA where
sfrom SZ (A0 c) = Rep (Here (c :* Nil))
sfrom SZ (A1 b) = Rep (There (Here (b :* Nil))
sfrom (SS SZ) (B0 c) = Rep (Here (c :* Nil))
sfrom (SS SZ) (B1 a) = Rep (Here (There (a :* Nil))
sto ...  inverse of sfrom
```
The attached files are the versions we get from attempting to use `languagego` or `languagepython` with
`genericsmrsop`.
## Environment
* GHC version used: 8.4.2, 8.6.5https://gitlab.haskell.org/ghc/ghc//issues/17225Infelicities in pure unifier20200310T14:18:56ZRichard Eisenbergrae@richarde.devInfelicities in pure unifierDuring code review on !852, Simon and I discovered a few infelicities in the pure unifier.
1. Many functions (ex: `unify_ty`, `uVar`) take a coercion between the kinds of the types being unified. It should be clarified what we are trying to say. To wit:
A. If matching: `kco :: subst(typeKind ty1) ~N typeKind ty2`
B. If unifying: `subst(kco) :: subst(ty1) ~N subst(typeKind ty2)`
2. All substitutions throughout GHC are kind preserving. Specifically, if we have a subst `S` containing a mapping `a :: k` to `t`, then it is always the case that `t :: S(k)`. This can be checked.
3. There is no `FunTy` case for `unify_ty` because it is handled by the tycon case. This should be commented. Specifically, we must make sure to unify the `RuntimeRep`s in the `FunTy`. This is indeed OK, but it should be made more clear.
4. `ty_co_match` is rather involved and may not be paying its way. Experiment what happens if it is removed.
5. The `ty_co_match` function is missing a case for `FunCo`. This is not actually a bug, because `ty_co_match` is a "best effort" function.
6. The `FunTy` case for `ty_co_match` incorrectly drops the `RuntimeRep`s.
7. We do *not* unify the kinds of type variables because the relationship between the kinds is passed in. See point (1).
8. We appear to be making fixpoints of substitutions even when doing oneway matching. As originally reported in https://gitlab.haskell.org/ghc/ghc/issues/16512#note_221617.
The only real bug here is (6), but it can only happen when performing coercion optimization on programs involving type families that twiddle `RuntimeRep`s in functions. I'm not going to try to find a test case.During code review on !852, Simon and I discovered a few infelicities in the pure unifier.
1. Many functions (ex: `unify_ty`, `uVar`) take a coercion between the kinds of the types being unified. It should be clarified what we are trying to say. To wit:
A. If matching: `kco :: subst(typeKind ty1) ~N typeKind ty2`
B. If unifying: `subst(kco) :: subst(ty1) ~N subst(typeKind ty2)`
2. All substitutions throughout GHC are kind preserving. Specifically, if we have a subst `S` containing a mapping `a :: k` to `t`, then it is always the case that `t :: S(k)`. This can be checked.
3. There is no `FunTy` case for `unify_ty` because it is handled by the tycon case. This should be commented. Specifically, we must make sure to unify the `RuntimeRep`s in the `FunTy`. This is indeed OK, but it should be made more clear.
4. `ty_co_match` is rather involved and may not be paying its way. Experiment what happens if it is removed.
5. The `ty_co_match` function is missing a case for `FunCo`. This is not actually a bug, because `ty_co_match` is a "best effort" function.
6. The `FunTy` case for `ty_co_match` incorrectly drops the `RuntimeRep`s.
7. We do *not* unify the kinds of type variables because the relationship between the kinds is passed in. See point (1).
8. We appear to be making fixpoints of substitutions even when doing oneway matching. As originally reported in https://gitlab.haskell.org/ghc/ghc/issues/16512#note_221617.
The only real bug here is (6), but it can only happen when performing coercion optimization on programs involving type families that twiddle `RuntimeRep`s in functions. I'm not going to try to find a test case.Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/17226Quantified constraints which specify associated type instances20200123T19:48:51ZsheafQuantified constraints which specify associated type instancesI have come across a situation which I believe could benefit from the ability to refine quantified constraints by adding constraints on the associated type instance declarations. For instance, consider a class with an associated type:
```haskell
class C a where
type T a :: Type
...
```
From what I understand, a quantified constraint of the form ```( forall a. C a => C (f a) )``` will be soluble when there is an instance of the form
```haskell
instance forall a. C a => C (f a)
```
My suggestion is to provide the ability to specify quantified constraints which restrict the associated type family instance declarations. In this case, we might want to insist upon the equation `type T (f a) = f (T a)`. One possible notation would use tuple and equality constraints (mirroring how one would encode this using `Dict`):
```haskell
forall a. C a => ( C (f a), T (f a) ~ f (T a) )
```
In solving this quantified constraint, we would discard all class instances which are not of the following form:
```haskell
instance forall a. C a => C (f a) where
type T (f a) = f (T a)
```
(I don't know how flexible we can afford to be in verifying this property, e.g. if the type family instance equations are not exactly as specified by the equality constraint but are equivalent to them, say after applying substitutions or using other equality constraints that might be available.)
### Example
To illustrate, I was working with the `Syntactic` type class
```haskell
class Syntactic a where
type Internal a
toAST :: a > AST (Internal a)
fromAST :: AST (Internal a) > a
```
and I wanted to restrict attention to functors `F` that are compatible with this type class, i.e. which have an instance declaration of the form
```haskell
instance Syntactic a => Syntactic (F a) where
type Internal (F a) = F (Internal a)
```
However, while I can write a quantified constraint `forall a. Syntactic a => Syntactic (f a)`, I cannot specify the additional requirement on the associated type family instance equation, so GHC will complain at usesites:
```
* Could not deduce: Internal (f a) ~ f (Internal a)
```
This can be worked around using `Dict ( Syntactic (f a), Internal (f a) ~ f (Internal a) )`, unfortunately forgoing the use of quantified constraints and introducing indirections (requiring matching on `Dict` to make the instances visible to GHC). Other than that I don't know of any tricks to bypass this limitation, but I may well be missing something (quite likely, as I don't have much experience with quantified constraints).I have come across a situation which I believe could benefit from the ability to refine quantified constraints by adding constraints on the associated type instance declarations. For instance, consider a class with an associated type:
```haskell
class C a where
type T a :: Type
...
```
From what I understand, a quantified constraint of the form ```( forall a. C a => C (f a) )``` will be soluble when there is an instance of the form
```haskell
instance forall a. C a => C (f a)
```
My suggestion is to provide the ability to specify quantified constraints which restrict the associated type family instance declarations. In this case, we might want to insist upon the equation `type T (f a) = f (T a)`. One possible notation would use tuple and equality constraints (mirroring how one would encode this using `Dict`):
```haskell
forall a. C a => ( C (f a), T (f a) ~ f (T a) )
```
In solving this quantified constraint, we would discard all class instances which are not of the following form:
```haskell
instance forall a. C a => C (f a) where
type T (f a) = f (T a)
```
(I don't know how flexible we can afford to be in verifying this property, e.g. if the type family instance equations are not exactly as specified by the equality constraint but are equivalent to them, say after applying substitutions or using other equality constraints that might be available.)
### Example
To illustrate, I was working with the `Syntactic` type class
```haskell
class Syntactic a where
type Internal a
toAST :: a > AST (Internal a)
fromAST :: AST (Internal a) > a
```
and I wanted to restrict attention to functors `F` that are compatible with this type class, i.e. which have an instance declaration of the form
```haskell
instance Syntactic a => Syntactic (F a) where
type Internal (F a) = F (Internal a)
```
However, while I can write a quantified constraint `forall a. Syntactic a => Syntactic (f a)`, I cannot specify the additional requirement on the associated type family instance equation, so GHC will complain at usesites:
```
* Could not deduce: Internal (f a) ~ f (Internal a)
```
This can be worked around using `Dict ( Syntactic (f a), Internal (f a) ~ f (Internal a) )`, unfortunately forgoing the use of quantified constraints and introducing indirections (requiring matching on `Dict` to make the instances visible to GHC). Other than that I don't know of any tricks to bypass this limitation, but I may well be missing something (quite likely, as I don't have much experience with quantified constraints).https://gitlab.haskell.org/ghc/ghc//issues/17306:kind! should adhere to freductiondepth20191009T09:52:21ZJakob Brünker:kind! should adhere to freductiondepth## Summary
`:kind!` consumes gigabytes of memory for a while and then fails with `*** Exception: stack overflow` (GHCi itself does **not** crash, as long as enough memory is available) if given a nonterminating typelevel expression, while using such a type elsewhere will immediately result in ghc announcing that it has reached the limit of it's reduction stack (with size 200 by default, specified by `freductiondepth`). I can't be sure if this is intended, since `freductiondepth` doesn't appear to be documented in the user guide, but it's not something I would have expected.
## Steps to reproduce
Type the following in GHCi:
```haskell
:set XTypeFamilies XUndecidableInstances
type family F where F = F
:kind! F
```
Typing something like `undefined :: F` works as expected, with an error message about having reached a reduction stack size of 201.
## Expected behavior
I would expect to get the current error message from `undefined :: F` for both `undefined :: F` **and** `:kind! F`.
## Environment
* GHC version used:
8.6.5, 8.8.1, HEAD (8.9.0.20191001)
* Operating System:
Windows, nixos
* System Architecture:
x86_64## Summary
`:kind!` consumes gigabytes of memory for a while and then fails with `*** Exception: stack overflow` (GHCi itself does **not** crash, as long as enough memory is available) if given a nonterminating typelevel expression, while using such a type elsewhere will immediately result in ghc announcing that it has reached the limit of it's reduction stack (with size 200 by default, specified by `freductiondepth`). I can't be sure if this is intended, since `freductiondepth` doesn't appear to be documented in the user guide, but it's not something I would have expected.
## Steps to reproduce
Type the following in GHCi:
```haskell
:set XTypeFamilies XUndecidableInstances
type family F where F = F
:kind! F
```
Typing something like `undefined :: F` works as expected, with an error message about having reached a reduction stack size of 201.
## Expected behavior
I would expect to get the current error message from `undefined :: F` for both `undefined :: F` **and** `:kind! F`.
## Environment
* GHC version used:
8.6.5, 8.8.1, HEAD (8.9.0.20191001)
* Operating System:
Windows, nixos
* System Architecture:
x86_64https://gitlab.haskell.org/ghc/ghc//issues/17311Type family equality gets stuck on types that fail the occurs check20201211T15:47:16ZisovectorType family equality gets stuck on types that fail the occurs check## Summary
A type family that should check two types for equality gets stuck, even though their equality would fail the occurs check.
## Steps to reproduce
The following program doesn't compile:
```haskell
{# LANGUAGE AllowAmbiguousTypes #}
module Occurs where
import Data.Functor.Identity
import Data.Proxy
type family Equal a b where
Equal a a = 'True
Equal a b = 'False
foo :: Proxy (Equal (Identity a) a) > Proxy 'False
foo = id
```
with error:
```
• Couldn't match type ‘Equal (Identity a) a’ with ‘'False’
Expected type: Proxy (Equal (Identity a) a) > Proxy 'False
Actual type: Proxy 'False > Proxy 'False
• In the expression: id
In an equation for ‘foo’: foo = id
• Relevant bindings include
foo :: Proxy (Equal (Identity a) a) > Proxy 'False
(bound at /home/sandy/Vikrem.hs:14:1)

14  foo = id

```
The `Equal` type family is stuck due to `a` being a variable, but the only way `Equal (Identity a) a ~ 'True` is for an infinite instantiation of `a`. As such, this thing should reduce.
## Expected behavior
I expect the above program to compile, with `Equal (Identity a) a` reducing to `'False`.
## Environment
* GHC version used: 8.6.5
Optional:
* Operating System: Archlinux
* System Architecture: x86_64## Summary
A type family that should check two types for equality gets stuck, even though their equality would fail the occurs check.
## Steps to reproduce
The following program doesn't compile:
```haskell
{# LANGUAGE AllowAmbiguousTypes #}
module Occurs where
import Data.Functor.Identity
import Data.Proxy
type family Equal a b where
Equal a a = 'True
Equal a b = 'False
foo :: Proxy (Equal (Identity a) a) > Proxy 'False
foo = id
```
with error:
```
• Couldn't match type ‘Equal (Identity a) a’ with ‘'False’
Expected type: Proxy (Equal (Identity a) a) > Proxy 'False
Actual type: Proxy 'False > Proxy 'False
• In the expression: id
In an equation for ‘foo’: foo = id
• Relevant bindings include
foo :: Proxy (Equal (Identity a) a) > Proxy 'False
(bound at /home/sandy/Vikrem.hs:14:1)

14  foo = id

```
The `Equal` type family is stuck due to `a` being a variable, but the only way `Equal (Identity a) a ~ 'True` is for an infinite instantiation of `a`. As such, this thing should reduce.
## Expected behavior
I expect the above program to compile, with `Equal (Identity a) a` reducing to `'False`.
## Environment
* GHC version used: 8.6.5
Optional:
* Operating System: Archlinux
* System Architecture: x86_64https://gitlab.haskell.org/ghc/ghc//issues/17323The Purely Kinded Type Invariant (PKTI) is not good enough20200124T11:45:59ZRichard Eisenbergrae@richarde.devThe Purely Kinded Type Invariant (PKTI) is not good enoughRequired reading: `Note [The Purely Kinded Type Invariant (PKTI)]` and `Note [mkAppTyM]`, both in TcHsType.
The PKTI has at least two problems.
1. Suppose we have the type `a > b` stored in `ty`. If we say `splitTyConApp ty`, we should expect to get `(funTyCon, [r1, r2, a, b])` where `a :: TYPE r1` and `b :: TYPE r2`. But what if `a` doesn't have type `TYPE r1` or `b` doesn't have type `TYPE r2`? This can happen if, say, `a :: kappa` and `kappa := TYPE r1`, but we haven't zonked. The PKTI must address this. This means that we will have to write `mkFunTyM` just like `mkAppTyM`. We might even need `mkTyConAppM` to handle the case when the tycon is `(>)`. :(
2. Nasty case 2 of `Note [mkAppTyM]` isn't sufficient. That case considers a type synonym. What about a type family?
```hs
type family F (a :: Type > Type) (b :: Type) where
F a b = a b
```
According to its current text of the PKTI, `F (a :: kappa1) (b :: kappa2)` satisfies the PKTI. Yet if we reduce this type family, `a b` does not satisfy the PKTI. Yet we sometimes reduce type families in a pure context (`normaliseType`) and, moreover, the main typefamilyreduction engine in TcFlatten does not respect the PKTI in this case as it does rewriting. (Actually, it does, because the flattener zonks thoroughly. But we're exploring the possibility of not zonking as thoroughly in the future. And, in any case, there is no documented connection between the flattener's desire to zonk and the PKTI.)
With some plumbing, etc., I'm confident we can fix (1). But I really have no idea how to fix (2). I worry we will have to abandon the idea of pure reductions, and we'll have to teach the flattener to check for "tricky tvs" (see `isTrickyTvBinder`) much like `mkAppTyM` does. Or, we can abandon pure reductions and just keep the flattener zonking thoroughly. :)Required reading: `Note [The Purely Kinded Type Invariant (PKTI)]` and `Note [mkAppTyM]`, both in TcHsType.
The PKTI has at least two problems.
1. Suppose we have the type `a > b` stored in `ty`. If we say `splitTyConApp ty`, we should expect to get `(funTyCon, [r1, r2, a, b])` where `a :: TYPE r1` and `b :: TYPE r2`. But what if `a` doesn't have type `TYPE r1` or `b` doesn't have type `TYPE r2`? This can happen if, say, `a :: kappa` and `kappa := TYPE r1`, but we haven't zonked. The PKTI must address this. This means that we will have to write `mkFunTyM` just like `mkAppTyM`. We might even need `mkTyConAppM` to handle the case when the tycon is `(>)`. :(
2. Nasty case 2 of `Note [mkAppTyM]` isn't sufficient. That case considers a type synonym. What about a type family?
```hs
type family F (a :: Type > Type) (b :: Type) where
F a b = a b
```
According to its current text of the PKTI, `F (a :: kappa1) (b :: kappa2)` satisfies the PKTI. Yet if we reduce this type family, `a b` does not satisfy the PKTI. Yet we sometimes reduce type families in a pure context (`normaliseType`) and, moreover, the main typefamilyreduction engine in TcFlatten does not respect the PKTI in this case as it does rewriting. (Actually, it does, because the flattener zonks thoroughly. But we're exploring the possibility of not zonking as thoroughly in the future. And, in any case, there is no documented connection between the flattener's desire to zonk and the PKTI.)
With some plumbing, etc., I'm confident we can fix (1). But I really have no idea how to fix (2). I worry we will have to abandon the idea of pure reductions, and we'll have to teach the flattener to check for "tricky tvs" (see `isTrickyTvBinder`) much like `mkAppTyM` does. Or, we can abandon pure reductions and just keep the flattener zonking thoroughly. :)https://gitlab.haskell.org/ghc/ghc//issues/17327Kindchecking associated types20200218T16:17:45ZmniipKindchecking associated types## Summary
When kind checking associated type declarations in an `instance` declaration, the instance context seems to be ignored.
## Steps to reproduce
Minimal complete example:
```haskell
{# LANGUAGE DataKinds, PolyKinds, TypeFamilies, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, TypeApplications #}
class C (k :: *) (a :: *) where
type F k a :: k
data D k (x :: k)
instance C k (D k x) where
type F k (D k x) = x  good
instance (k ~ l) => C l (D k x) where
type F l (D k x) = x  bad
{
b.hs:11:22: error:
• Expected kind ‘l’, but ‘x’ has kind ‘k’
• In the type ‘x’
In the type instance declaration for ‘F’
In the instance declaration for ‘C l (D k x)’

11  type F l (D k x) = x  bad
 ^
}
```
## Expected behavior
The second instance should kindcheck (it has better instance resolution properties than the first which is why we want it).
## Environment
Tested on GHC 8.6.5 and GHC HEAD## Summary
When kind checking associated type declarations in an `instance` declaration, the instance context seems to be ignored.
## Steps to reproduce
Minimal complete example:
```haskell
{# LANGUAGE DataKinds, PolyKinds, TypeFamilies, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, TypeApplications #}
class C (k :: *) (a :: *) where
type F k a :: k
data D k (x :: k)
instance C k (D k x) where
type F k (D k x) = x  good
instance (k ~ l) => C l (D k x) where
type F l (D k x) = x  bad
{
b.hs:11:22: error:
• Expected kind ‘l’, but ‘x’ has kind ‘k’
• In the type ‘x’
In the type instance declaration for ‘F’
In the instance declaration for ‘C l (D k x)’

11  type F l (D k x) = x  bad
 ^
}
```
## Expected behavior
The second instance should kindcheck (it has better instance resolution properties than the first which is why we want it).
## Environment
Tested on GHC 8.6.5 and GHC HEADhttps://gitlab.haskell.org/ghc/ghc//issues/17328GeneralizedNewtypeDeriving should not require that constructor be in scope20200703T17:15:30ZRichard Eisenbergrae@richarde.devGeneralizedNewtypeDeriving should not require that constructor be in scopeAs I learned perusing !1916 (but you don't need to read that MR), `GeneralizedNewtypeDeriving` requires that the constructor of the newtype in question be in scope. Yet this isn't really necessary:
A.hs:
```hs
module A where
newtype N1 = MkN1 N2
newtype N2 = MkN2 N1
instance Eq N2 where
(==) = const (const False)
```
B.hs:
```hs
{# LANGUAGE DerivingStrategies, StandaloneDeriving, GeneralizedNewtypeDeriving,
DerivingVia #}
module B where
import A ( N1, N2(..) )
import Data.Coerce
 This fails:
 deriving newtype instance Eq N1
 This succeeds:
 deriving via N2 instance Eq N1
 This succeeds:
instance Eq N1 where
(==) = coerce ((==) :: N2 > N2 > Bool)
```
I would think that the three possible instance declarations in B.hs would all be completely equivalent. Yet the first is rejected while the last two are accepted.
This example is indeed silly, but it's possible to make mutuallyrecursive newtypes that are not silly (by using e.g. `Maybe` or `Either` to break the loop).
Conclusion: The `newtype` strategy should not require the newtype constructor to be in scope. Instead, it should rely on the `Coercible` machinery to trigger the usual case where we need the constructor in scope. Of course, we should make sure that the error message is sensible when this happens.As I learned perusing !1916 (but you don't need to read that MR), `GeneralizedNewtypeDeriving` requires that the constructor of the newtype in question be in scope. Yet this isn't really necessary:
A.hs:
```hs
module A where
newtype N1 = MkN1 N2
newtype N2 = MkN2 N1
instance Eq N2 where
(==) = const (const False)
```
B.hs:
```hs
{# LANGUAGE DerivingStrategies, StandaloneDeriving, GeneralizedNewtypeDeriving,
DerivingVia #}
module B where
import A ( N1, N2(..) )
import Data.Coerce
 This fails:
 deriving newtype instance Eq N1
 This succeeds:
 deriving via N2 instance Eq N1
 This succeeds:
instance Eq N1 where
(==) = coerce ((==) :: N2 > N2 > Bool)
```
I would think that the three possible instance declarations in B.hs would all be completely equivalent. Yet the first is rejected while the last two are accepted.
This example is indeed silly, but it's possible to make mutuallyrecursive newtypes that are not silly (by using e.g. `Maybe` or `Either` to break the loop).
Conclusion: The `newtype` strategy should not require the newtype constructor to be in scope. Instead, it should rely on the `Coercible` machinery to trigger the usual case where we need the constructor in scope. Of course, we should make sure that the error message is sensible when this happens.https://gitlab.haskell.org/ghc/ghc//issues/17333Coercible solver does not look through "class newtypes"20210216T21:35:31ZRyan ScottCoercible solver does not look through "class newtypes"The code below makes use of the "class newtype" design pattern:
```hs
class Show a => MyShow a
instance Show a => MyShow a
```
`MyShow` is a newtype around `Show` in the sense that when compiled to Core, a `MyShow` dictionary is literally a newtype around `Show`. Unfortunately, this newtype treatment does not extend to the `Coercible` solver, as the following example demonstrates:
```hs
{# LANGUAGE ConstraintKinds #}
{# LANGUAGE FlexibleContexts #}
{# LANGUAGE FlexibleInstances #}
{# LANGUAGE MonoLocalBinds #}
{# LANGUAGE QuantifiedConstraints #}
{# LANGUAGE RankNTypes #}
{# LANGUAGE UndecidableInstances #}
{# LANGUAGE UndecidableSuperClasses #}
module Bug where
import Data.Coerce
class Show a => MyShow a
instance Show a => MyShow a
newtype T1 a = MkT1 ( Show a => a > a > String)
newtype T2 a = MkT2 (MyShow a => a > a > String)
f :: T1 a > T2 a
f = coerce
```
```
$ /opt/ghc/8.8.1/bin/ghc Bug.hs
[1 of 1] Compiling Bug ( Bug.hs, Bug.o )
Bug.hs:20:5: error:
• Couldn't match representation of type ‘MyShow a’
with that of ‘Show a’
arising from a use of ‘coerce’
The data constructor ‘Bug.C:MyShow’
of newtype ‘MyShow’ is not in scope
• In the expression: coerce
In an equation for ‘f’: f = coerce
• Relevant bindings include
f :: T1 a > T2 a (bound at Bug.hs:20:1)

20  f = coerce
 ^^^^^^
```
Somewhat surprisingly, this does not work. Even the error message indicates that `MyShow` is a newtype (which is a bit odd, but whatever), but since the internal `C:MyShow` constructor is not exposed, the `Coercible` solver doesn't have enough information to proceed.
If the following change is applied to GHC, then it typechecks:
```diff
diff git a/compiler/typecheck/FamInst.hs b/compiler/typecheck/FamInst.hs
index a339dd7b57..8640b3e3e0 100644
 a/compiler/typecheck/FamInst.hs
+++ b/compiler/typecheck/FamInst.hs
@@ 41,7 +41,7 @@ import Name
import Pair
import Panic
import VarSet
import Bag( Bag, unionBags, unitBag )
+import Bag( Bag, emptyBag, unionBags, unitBag )
import Control.Monad
#include "HsVersions.h"
@@ 577,6 +577,10 @@ tcTopNormaliseNewTypeTF_maybe faminsts rdr_env ty
= mapStepResult (\co > (unitBag gre, co)) $
unwrapNewTypeStepper rec_nts tc tys
+  isClassTyCon tc && isNewTyCon tc
+ = mapStepResult (\co > (emptyBag, co)) $
+ unwrapNewTypeStepper rec_nts tc tys
+
 otherwise
= NS_Done
```
The simplified example above is somewhat contrived, although I have legitimate need of this feature in more complicated scenarios like this one (inspired by [Generic Programming of All Kinds](https://victorcmiraldo.github.io/data/hask2018_draft.pdf)):
```hs
{# LANGUAGE ConstraintKinds #}
{# LANGUAGE DataKinds #}
{# LANGUAGE FlexibleContexts #}
{# LANGUAGE FlexibleInstances #}
{# LANGUAGE GADTs #}
{# LANGUAGE ImpredicativeTypes #}
{# LANGUAGE MultiParamTypeClasses #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE QuantifiedConstraints #}
{# LANGUAGE RankNTypes #}
{# LANGUAGE TypeApplications #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE TypeOperators #}
{# LANGUAGE UndecidableInstances #}
{# LANGUAGE UndecidableSuperClasses #}
module GOAK where
import Data.Coerce
import Data.Kind
newtype T = MkT ((forall a. Show a) => Int)
type TRep = Field (ForAllQ (Kon Show :@: Var VZ) :=>>: Kon Int) LoT0
f :: T > TRep
f (MkT x) = Field (coerce @((forall a. Show a) => Int)
@(Interpret (ForAllQ (Kon Show :@: Var VZ) :=>>: Kon Int) LoT0)
x)

infixr 5 :&&:
data LoT :: Type > Type where
LoT0 :: LoT Type
(:&&:) :: k > LoT ks > LoT (k > ks)
type family HeadLoT (tys :: LoT (k > k')) :: k where
HeadLoT (a :&&: _) = a
type family TailLoT (tys :: LoT (k > k')) :: LoT k' where
TailLoT (_ :&&: as) = as
data TyVar :: Type > Type > Type where
VZ :: TyVar (x > xs) x
VS :: TyVar xs k > TyVar (x > xs) k
data Atom :: Type > Type > Type where
Var :: TyVar d k > Atom d k
Kon :: k > Atom d k
(:@:) :: Atom d (k1 > k2) > Atom d k1 > Atom d k2
(:=>>:) :: Atom d Constraint > Atom d Type > Atom d Type
ForAllQ :: Atom (d1 > d) Constraint > Atom d Constraint
type family InterpretVar (t :: TyVar d k) (tys :: LoT d) :: k where
InterpretVar 'VZ tys = HeadLoT tys
InterpretVar ('VS v) tys = InterpretVar v (TailLoT tys)
type family Interpret (t :: Atom d k) (tys :: LoT d) :: k where
Interpret ('Var v) tys = InterpretVar v tys
Interpret ('Kon t) tys = t
Interpret (f ':@: x) tys = (Interpret f tys) (Interpret x tys)
Interpret (c ':=>>: f) tys = SuchThatI c f tys
Interpret (ForAllQ f) tys = ForAllQI f tys
newtype SuchThatI :: Atom d Constraint > Atom d Type > LoT d > Type where
SuchThatI :: (Interpret c tys => Interpret f tys) > SuchThatI c f tys
class (forall t. WrappedQI f (t ':&&: tys)) => ForAllQI (f :: Atom (d1 > d) Constraint) (tys :: LoT d)
instance (forall t. WrappedQI f (t ':&&: tys)) => ForAllQI (f :: Atom (d1 > d) Constraint) (tys :: LoT d)
class Interpret f tys => WrappedQI (f :: Atom d Constraint) (tys :: LoT d)
instance Interpret f tys => WrappedQI (f :: Atom d Constraint) (tys :: LoT d)
newtype Field :: Atom d Type > LoT d > Type where
Field :: { unField :: Interpret t x } > Field t x
```
`f` will not typecheck without the ability to coerce from `ForAllQI f tys` to `forall t. WrappedQI f (t ':&&: tys)`. Moreover, it would be extremely difficult to write `f` _without_ `coerce`.The code below makes use of the "class newtype" design pattern:
```hs
class Show a => MyShow a
instance Show a => MyShow a
```
`MyShow` is a newtype around `Show` in the sense that when compiled to Core, a `MyShow` dictionary is literally a newtype around `Show`. Unfortunately, this newtype treatment does not extend to the `Coercible` solver, as the following example demonstrates:
```hs
{# LANGUAGE ConstraintKinds #}
{# LANGUAGE FlexibleContexts #}
{# LANGUAGE FlexibleInstances #}
{# LANGUAGE MonoLocalBinds #}
{# LANGUAGE QuantifiedConstraints #}
{# LANGUAGE RankNTypes #}
{# LANGUAGE UndecidableInstances #}
{# LANGUAGE UndecidableSuperClasses #}
module Bug where
import Data.Coerce
class Show a => MyShow a
instance Show a => MyShow a
newtype T1 a = MkT1 ( Show a => a > a > String)
newtype T2 a = MkT2 (MyShow a => a > a > String)
f :: T1 a > T2 a
f = coerce
```
```
$ /opt/ghc/8.8.1/bin/ghc Bug.hs
[1 of 1] Compiling Bug ( Bug.hs, Bug.o )
Bug.hs:20:5: error:
• Couldn't match representation of type ‘MyShow a’
with that of ‘Show a’
arising from a use of ‘coerce’
The data constructor ‘Bug.C:MyShow’
of newtype ‘MyShow’ is not in scope
• In the expression: coerce
In an equation for ‘f’: f = coerce
• Relevant bindings include
f :: T1 a > T2 a (bound at Bug.hs:20:1)

20  f = coerce
 ^^^^^^
```
Somewhat surprisingly, this does not work. Even the error message indicates that `MyShow` is a newtype (which is a bit odd, but whatever), but since the internal `C:MyShow` constructor is not exposed, the `Coercible` solver doesn't have enough information to proceed.
If the following change is applied to GHC, then it typechecks:
```diff
diff git a/compiler/typecheck/FamInst.hs b/compiler/typecheck/FamInst.hs
index a339dd7b57..8640b3e3e0 100644
 a/compiler/typecheck/FamInst.hs
+++ b/compiler/typecheck/FamInst.hs
@@ 41,7 +41,7 @@ import Name
import Pair
import Panic
import VarSet
import Bag( Bag, unionBags, unitBag )
+import Bag( Bag, emptyBag, unionBags, unitBag )
import Control.Monad
#include "HsVersions.h"
@@ 577,6 +577,10 @@ tcTopNormaliseNewTypeTF_maybe faminsts rdr_env ty
= mapStepResult (\co > (unitBag gre, co)) $
unwrapNewTypeStepper rec_nts tc tys
+  isClassTyCon tc && isNewTyCon tc
+ = mapStepResult (\co > (emptyBag, co)) $
+ unwrapNewTypeStepper rec_nts tc tys
+
 otherwise
= NS_Done
```
The simplified example above is somewhat contrived, although I have legitimate need of this feature in more complicated scenarios like this one (inspired by [Generic Programming of All Kinds](https://victorcmiraldo.github.io/data/hask2018_draft.pdf)):
```hs
{# LANGUAGE ConstraintKinds #}
{# LANGUAGE DataKinds #}
{# LANGUAGE FlexibleContexts #}
{# LANGUAGE FlexibleInstances #}
{# LANGUAGE GADTs #}
{# LANGUAGE ImpredicativeTypes #}
{# LANGUAGE MultiParamTypeClasses #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE QuantifiedConstraints #}
{# LANGUAGE RankNTypes #}
{# LANGUAGE TypeApplications #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE TypeOperators #}
{# LANGUAGE UndecidableInstances #}
{# LANGUAGE UndecidableSuperClasses #}
module GOAK where
import Data.Coerce
import Data.Kind
newtype T = MkT ((forall a. Show a) => Int)
type TRep = Field (ForAllQ (Kon Show :@: Var VZ) :=>>: Kon Int) LoT0
f :: T > TRep
f (MkT x) = Field (coerce @((forall a. Show a) => Int)
@(Interpret (ForAllQ (Kon Show :@: Var VZ) :=>>: Kon Int) LoT0)
x)

infixr 5 :&&:
data LoT :: Type > Type where
LoT0 :: LoT Type
(:&&:) :: k > LoT ks > LoT (k > ks)
type family HeadLoT (tys :: LoT (k > k')) :: k where
HeadLoT (a :&&: _) = a
type family TailLoT (tys :: LoT (k > k')) :: LoT k' where
TailLoT (_ :&&: as) = as
data TyVar :: Type > Type > Type where
VZ :: TyVar (x > xs) x
VS :: TyVar xs k > TyVar (x > xs) k
data Atom :: Type > Type > Type where
Var :: TyVar d k > Atom d k
Kon :: k > Atom d k
(:@:) :: Atom d (k1 > k2) > Atom d k1 > Atom d k2
(:=>>:) :: Atom d Constraint > Atom d Type > Atom d Type
ForAllQ :: Atom (d1 > d) Constraint > Atom d Constraint
type family InterpretVar (t :: TyVar d k) (tys :: LoT d) :: k where
InterpretVar 'VZ tys = HeadLoT tys
InterpretVar ('VS v) tys = InterpretVar v (TailLoT tys)
type family Interpret (t :: Atom d k) (tys :: LoT d) :: k where
Interpret ('Var v) tys = InterpretVar v tys
Interpret ('Kon t) tys = t
Interpret (f ':@: x) tys = (Interpret f tys) (Interpret x tys)
Interpret (c ':=>>: f) tys = SuchThatI c f tys
Interpret (ForAllQ f) tys = ForAllQI f tys
newtype SuchThatI :: Atom d Constraint > Atom d Type > LoT d > Type where
SuchThatI :: (Interpret c tys => Interpret f tys) > SuchThatI c f tys
class (forall t. WrappedQI f (t ':&&: tys)) => ForAllQI (f :: Atom (d1 > d) Constraint) (tys :: LoT d)
instance (forall t. WrappedQI f (t ':&&: tys)) => ForAllQI (f :: Atom (d1 > d) Constraint) (tys :: LoT d)
class Interpret f tys => WrappedQI (f :: Atom d Constraint) (tys :: LoT d)
instance Interpret f tys => WrappedQI (f :: Atom d Constraint) (tys :: LoT d)
newtype Field :: Atom d Type > LoT d > Type where
Field :: { unField :: Interpret t x } > Field t x
```
`f` will not typecheck without the ability to coerce from `ForAllQI f tys` to `forall t. WrappedQI f (t ':&&: tys)`. Moreover, it would be extremely difficult to write `f` _without_ `coerce`.https://gitlab.haskell.org/ghc/ghc//issues/17368Implement homogeneous equality20210616T15:54:59ZRichard Eisenbergrae@richarde.devImplement homogeneous equalityAs observed in [two](https://repository.brynmawr.edu/cgi/viewcontent.cgi?article=1076&context=compsci_pubs) [papers](https://richarde.dev/papers/2019/deproles/deproles.pdf), the primitive equality type in GHC can be made homogeneous. This is both a simplification over the status quo (heterogeneous equality) and an important step toward implementing dependent types.
This ticket is to track this change.
Step 1: Modify the typechecker to use predicates instead of types internally. This will essentially be a glorification of `PredTree` (renamed `Pred`), and a `CtEvidence` will now store a `Pred`, not a `PredType`.
See also https://gitlab.haskell.org/ghc/ghc/wikis/dependenthaskell/phase2, which has much discussion.As observed in [two](https://repository.brynmawr.edu/cgi/viewcontent.cgi?article=1076&context=compsci_pubs) [papers](https://richarde.dev/papers/2019/deproles/deproles.pdf), the primitive equality type in GHC can be made homogeneous. This is both a simplification over the status quo (heterogeneous equality) and an important step toward implementing dependent types.
This ticket is to track this change.
Step 1: Modify the typechecker to use predicates instead of types internally. This will essentially be a glorification of `PredTree` (renamed `Pred`), and a `CtEvidence` will now store a `Pred`, not a `PredType`.
See also https://gitlab.haskell.org/ghc/ghc/wikis/dependenthaskell/phase2, which has much discussion.Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/17432Wildcards in standalone kind signatures20200112T20:22:51ZRichard Eisenbergrae@richarde.devWildcards in standalone kind signaturesWe should allow partial kind signatures as well as partial type signatures:
```hs
type Maybe :: _ > Type
data Maybe a = Nothing  Just a
type Proxy :: forall (k :: _). k > _
data Proxy = MkP
```
Of course, this would mean that polymorphic recursion would not be allowed. It's all just like at the term level.We should allow partial kind signatures as well as partial type signatures:
```hs
type Maybe :: _ > Type
data Maybe a = Nothing  Just a
type Proxy :: forall (k :: _). k > _
data Proxy = MkP
```
Of course, this would mean that polymorphic recursion would not be allowed. It's all just like at the term level.https://gitlab.haskell.org/ghc/ghc//issues/17545Coercion variables appearing where they shouldn't20200120T00:24:32ZKrzysztof GogolewskiCoercion variables appearing where they shouldn'tDuring review of !2268, we've discovered a few places where a coercion variable can appear where it shouldn't. Those are calls to "OrCoVar" functions in:
* [ ] `newLocal` in `MkId`
* [ ] `bindIfaceId` in `TcIface`
* [ ] `tcPatBndr` in `TcPat`
that happen when running tests T13990 T14285 T15648.
The goal is to fix this, or come up with a convincing reason that a coercion makes sense there.During review of !2268, we've discovered a few places where a coercion variable can appear where it shouldn't. Those are calls to "OrCoVar" functions in:
* [ ] `newLocal` in `MkId`
* [ ] `bindIfaceId` in `TcIface`
* [ ] `tcPatBndr` in `TcPat`
that happen when running tests T13990 T14285 T15648.
The goal is to fix this, or come up with a convincing reason that a coercion makes sense there.https://gitlab.haskell.org/ghc/ghc//issues/17563Validity check quantified constraints20201213T22:02:03ZRichard Eisenbergrae@richarde.devValidity check quantified constraintsThis module is accepted:
```hs
{# LANGUAGE QuantifiedConstraints #}
module Bug2 where
blah :: (forall a. a b ~ a c) => b > c
blah = undefined
```
But it shouldn't be: it uses `~` with neither `GADTs` nor `TypeFamilies` enabled.This module is accepted:
```hs
{# LANGUAGE QuantifiedConstraints #}
module Bug2 where
blah :: (forall a. a b ~ a c) => b > c
blah = undefined
```
But it shouldn't be: it uses `~` with neither `GADTs` nor `TypeFamilies` enabled.8.10.2https://gitlab.haskell.org/ghc/ghc//issues/17564Don't drop derived quantified constraints20191211T09:48:10ZRichard Eisenbergrae@richarde.devDon't drop derived quantified constraintsIn looking at the way quantified constraints are handled, I noticed that we drop derived quantified constraints (in `TcCanonical.solveForAll`). I don't see a reason why this is a good idea. And indeed, it causes trouble:
```hs
{# LANGUAGE QuantifiedConstraints, MultiParamTypeClasses,
KindSignatures, FlexibleInstances, TypeFamilies #}
module Bug where
import Data.Kind
class (forall (a :: Type > Type). a b ~ a c) => C b c
instance C a a
class (b ~ c) => D b c
instance D a a
foo :: C a b => a > b
foo = undefined
bar = foo
food :: D a b => a > b
food = undefined
bard = food
```
`C` and `D` should really behave identically. Yet `bar` is rejected while `bard` is accepted.
Note that the monomorphism restriction forces us to solve, not quantify over, the `C` and `D` constraints. This is intentional in this test case.
Normally, the superclasses of a wanted are emitted as derived constraints. In the case of `bard`, we start with `[W] D alpha beta`, which doesn't make progress. So we get `[D] alpha ~ beta`, which unifies the two, and then `[W] D alpha alpha` is easily dispatched. But in `bar` the `[D] forall a. a alpha ~ a beta` is dropped, leading to rejection.
The kind signature in the test case is needed because of #17562.In looking at the way quantified constraints are handled, I noticed that we drop derived quantified constraints (in `TcCanonical.solveForAll`). I don't see a reason why this is a good idea. And indeed, it causes trouble:
```hs
{# LANGUAGE QuantifiedConstraints, MultiParamTypeClasses,
KindSignatures, FlexibleInstances, TypeFamilies #}
module Bug where
import Data.Kind
class (forall (a :: Type > Type). a b ~ a c) => C b c
instance C a a
class (b ~ c) => D b c
instance D a a
foo :: C a b => a > b
foo = undefined
bar = foo
food :: D a b => a > b
food = undefined
bard = food
```
`C` and `D` should really behave identically. Yet `bar` is rejected while `bard` is accepted.
Note that the monomorphism restriction forces us to solve, not quantify over, the `C` and `D` constraints. This is intentional in this test case.
Normally, the superclasses of a wanted are emitted as derived constraints. In the case of `bard`, we start with `[W] D alpha beta`, which doesn't make progress. So we get `[D] alpha ~ beta`, which unifies the two, and then `[W] D alpha alpha` is easily dispatched. But in `bar` the `[D] forall a. a alpha ~ a beta` is dropped, leading to rejection.
The kind signature in the test case is needed because of #17562.https://gitlab.haskell.org/ghc/ghc//issues/17644Loop in the constraint solver around variables free in kinds20200120T18:20:09ZRichard Eisenbergrae@richarde.devLoop in the constraint solver around variables free in kindsSpun off from the bowels of #17323 (https://gitlab.haskell.org/ghc/ghc/issues/17323#note_243178, https://gitlab.haskell.org/ghc/ghc/issues/17323#note_243577, https://gitlab.haskell.org/ghc/ghc/issues/17323#note_244748), but I think orthogonal to that ticket. No need to read that ticket to understand this one.
Here is a simple form of the potential problem (due to @simonpj):
```
Inert set:
[G] b ~ a
Work item:
[G] (a :: *) ~ (c :: b > *) (d :: b)
```
I think GHC will add that work item to the inert set, despite the fact that it seems loopy.
And in this example, I think we'll actually get a loop:
```
a :: e
b :: d > e
c :: d
d :: Type
e :: Type
f :: e > Type
g :: d > Type
inert set:
[D] a ~ b c
[D] e ~ g c
[G] g1 :: d ~ f a  just having `a` here would violate K3a of Note [Extending the inert equalities]
work item: [D] e ~ f a
```
Let's see what happens.
1. `can_eq_nc'` will get to its flattening clause, so both sides get flattened, yielding `[D] g c ~ f (b c)`.
2. `can_eq_nc'` then decomposes to `[D] g ~ f` and `[D] c ~ b c`. We'll continue here with the latter.
3. On the new work item `[D] c ~ b c`, `can_eq_nc'` will get to its flattening clause, so both sides get flattened, causing no change.
4. Then, we go to `canEqTyVar`. We have `c :: d` but `b c :: e`, so we flatten both kinds. We thus get `[D] (c > g1) ~ b c`, where `g1 :: d ~ f a` comes from flattening. We then emit `[D] f a ~ e`. The first is irreducible, but the second brings us right back where we started. (Note that `e` isn't rewritten by flattening because the equality for `e` is a Derived, which cannot be used to rewrite a kind.)
[This comment](https://gitlab.haskell.org/ghc/ghc/issues/17644#note_245566) below shows `f8` which shows an actual loop from this case. Plus: the other examples there show cases where simply reordering the constraints in a type changes the accept/reject behaviour; this is Bad.Spun off from the bowels of #17323 (https://gitlab.haskell.org/ghc/ghc/issues/17323#note_243178, https://gitlab.haskell.org/ghc/ghc/issues/17323#note_243577, https://gitlab.haskell.org/ghc/ghc/issues/17323#note_244748), but I think orthogonal to that ticket. No need to read that ticket to understand this one.
Here is a simple form of the potential problem (due to @simonpj):
```
Inert set:
[G] b ~ a
Work item:
[G] (a :: *) ~ (c :: b > *) (d :: b)
```
I think GHC will add that work item to the inert set, despite the fact that it seems loopy.
And in this example, I think we'll actually get a loop:
```
a :: e
b :: d > e
c :: d
d :: Type
e :: Type
f :: e > Type
g :: d > Type
inert set:
[D] a ~ b c
[D] e ~ g c
[G] g1 :: d ~ f a  just having `a` here would violate K3a of Note [Extending the inert equalities]
work item: [D] e ~ f a
```
Let's see what happens.
1. `can_eq_nc'` will get to its flattening clause, so both sides get flattened, yielding `[D] g c ~ f (b c)`.
2. `can_eq_nc'` then decomposes to `[D] g ~ f` and `[D] c ~ b c`. We'll continue here with the latter.
3. On the new work item `[D] c ~ b c`, `can_eq_nc'` will get to its flattening clause, so both sides get flattened, causing no change.
4. Then, we go to `canEqTyVar`. We have `c :: d` but `b c :: e`, so we flatten both kinds. We thus get `[D] (c > g1) ~ b c`, where `g1 :: d ~ f a` comes from flattening. We then emit `[D] f a ~ e`. The first is irreducible, but the second brings us right back where we started. (Note that `e` isn't rewritten by flattening because the equality for `e` is a Derived, which cannot be used to rewrite a kind.)
[This comment](https://gitlab.haskell.org/ghc/ghc/issues/17644#note_245566) below shows `f8` which shows an actual loop from this case. Plus: the other examples there show cases where simply reordering the constraints in a type changes the accept/reject behaviour; this is Bad.https://gitlab.haskell.org/ghc/ghc//issues/17679Superclass expansion fails in instance declaration20200115T18:01:59ZRichard Eisenbergrae@richarde.devSuperclass expansion fails in instance declarationI'm sure I'm doing something very silly.
```hs
{# LANGUAGE FlexibleInstances, UndecidableInstances #}
module Bug where
class A a
class A a => B a
class A a => C a
instance B a => C a
```
GHC rejects, saying it can't prove `A a`, required in order to write the `C a` instance. But shouldn't my `B a` constraint imply `A a`?
Help?I'm sure I'm doing something very silly.
```hs
{# LANGUAGE FlexibleInstances, UndecidableInstances #}
module Bug where
class A a
class A a => B a
class A a => C a
instance B a => C a
```
GHC rejects, saying it can't prove `A a`, required in order to write the `C a` instance. But shouldn't my `B a` constraint imply `A a`?
Help?https://gitlab.haskell.org/ghc/ghc//issues/17717Refactor mapType/mapCoercion so that they inline20200323T13:53:00ZRichard Eisenbergrae@richarde.devRefactor mapType/mapCoercion so that they inline`mapType` and `mapCoercion` are very convenient functions for writing transformations over types and coercions. But they current don't inline properly, meaning that the `TyCoMapper` that describes their behavior is not inlined, and thus preventing other optimizations.
Instead, they should be refactored to be like https://gitlab.haskell.org/ghc/ghc/blob/wip/T17509/compiler/types/TyCoRep.hs#L1742, where we have carefully ensured that similar functions inline.
Main work done in #!2683.
Remaining task: use `mapType` more!`mapType` and `mapCoercion` are very convenient functions for writing transformations over types and coercions. But they current don't inline properly, meaning that the `TyCoMapper` that describes their behavior is not inlined, and thus preventing other optimizations.
Instead, they should be refactored to be like https://gitlab.haskell.org/ghc/ghc/blob/wip/T17509/compiler/types/TyCoRep.hs#L1742, where we have carefully ensured that similar functions inline.
Main work done in #!2683.
Remaining task: use `mapType` more!https://gitlab.haskell.org/ghc/ghc//issues/17718Refactor solver to leave breadcrumbs20200120T21:32:21ZRichard Eisenbergrae@richarde.devRefactor solver to leave breadcrumbsToday, the solver works hard to find how givens can imply wanteds. If it fails, it exits with unsolved wanteds. These wanteds are then scrutinized carefully in the TcErrors module in order to produce nice, userreadable error messages. However, the current design means that TcErrors needs to do much work trying to analyze the tea leaves that the solver has left behind. That is, it must reconstruct *why* a constraint was failed to be solved. This involves some duplicate code and duplicate work (such as looking in instance environments).
Instead, we can imagine a structure, stored within a `CtLoc`, that records the solver's movements, including movements it failed to make (such as "tried to unify, but hit an occurscheck failure"). This structure could then be consumed in TcErrors. Effectively, this means that the solver could more directly communicate with users and explain its reasoning. We might also imagine a future where users can query GHC for information about even typecorrect programs.
This ticket is to track this refactoring opportunity.Today, the solver works hard to find how givens can imply wanteds. If it fails, it exits with unsolved wanteds. These wanteds are then scrutinized carefully in the TcErrors module in order to produce nice, userreadable error messages. However, the current design means that TcErrors needs to do much work trying to analyze the tea leaves that the solver has left behind. That is, it must reconstruct *why* a constraint was failed to be solved. This involves some duplicate code and duplicate work (such as looking in instance environments).
Instead, we can imagine a structure, stored within a `CtLoc`, that records the solver's movements, including movements it failed to make (such as "tried to unify, but hit an occurscheck failure"). This structure could then be consumed in TcErrors. Effectively, this means that the solver could more directly communicate with users and explain its reasoning. We might also imagine a future where users can query GHC for information about even typecorrect programs.
This ticket is to track this refactoring opportunity.https://gitlab.haskell.org/ghc/ghc//issues/17719Note [Do not add duplicate quantified instances] is simplistic, causing rejec...20200714T19:14:38ZRichard Eisenbergrae@richarde.devNote [Do not add duplicate quantified instances] is simplistic, causing rejection of programsCopied wholesale from https://gitlab.haskell.org/ghc/ghc/merge_requests/2283#note_242042:
Consider
```haskell
{# LANGUAGE QuantifiedConstraints, ConstraintKinds,
ExistentialQuantification #}
module Bug where
class C1 a
class (forall z. C1 z) => C2 y
class (forall y. C2 y) => C3 x
data Dict c = c => Dict
foo :: (C2 a, C3 a) => a > Dict (C1 a)
foo _ = Dict
```
Amazingly, with *either* `C2 a` or `C3 a`, `foo` is accepted. But with both, it is rejected.
The problem is that, after eagerly expanding superclasses of quantified constraints (that's the new bit), we end up with
```
[G] g1 :: forall z. C1 z  from the C2 a constraint
[G] g2 :: forall y z. C1 z  from the C3 a constraint
```
So when we want to solve `C1 a`, we don't know which quantified constraint to use, and so we stop. (Also strange: `g2` is quantified over the unused `y`. It's clear where this comes from, and it seems harmless, but it's a bit strange. This detail is *not* salient. It is *not* the reason we're struggling here.) This has been seen before, in another guise: #15244. And we have
```
{ Note [Do not add duplicate quantified instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this (#15244):
f :: (C g, D g) => ....
class S g => C g where ...
class S g => D g where ...
class (forall a. Eq a => Eq (g a)) => S g where ...
Then in f's RHS there are two identical quantified constraints
available, one via the superclasses of C and one via the superclasses
of D. The two are identical, and it seems wrong to reject the program
because of that. But without doing duplicateelimination we will have
two matching QCInsts when we try to solve constraints arising from f's
RHS.
The simplest thing is simply to eliminate duplicates, which we do here.
}
```
which is duly implemented. However, here, we don't have duplicates  we have nearduplicates, which are not caught by the simple (`tcEqType`) check.
I wonder if the way forward is to really try to "solve" quantified instances. That is, before labeling them inert, we try to interact them with inerts. Then, we might discover that one constraint is implied by another, which will get rid of this problem (and replace that Note).Copied wholesale from https://gitlab.haskell.org/ghc/ghc/merge_requests/2283#note_242042:
Consider
```haskell
{# LANGUAGE QuantifiedConstraints, ConstraintKinds,
ExistentialQuantification #}
module Bug where
class C1 a
class (forall z. C1 z) => C2 y
class (forall y. C2 y) => C3 x
data Dict c = c => Dict
foo :: (C2 a, C3 a) => a > Dict (C1 a)
foo _ = Dict
```
Amazingly, with *either* `C2 a` or `C3 a`, `foo` is accepted. But with both, it is rejected.
The problem is that, after eagerly expanding superclasses of quantified constraints (that's the new bit), we end up with
```
[G] g1 :: forall z. C1 z  from the C2 a constraint
[G] g2 :: forall y z. C1 z  from the C3 a constraint
```
So when we want to solve `C1 a`, we don't know which quantified constraint to use, and so we stop. (Also strange: `g2` is quantified over the unused `y`. It's clear where this comes from, and it seems harmless, but it's a bit strange. This detail is *not* salient. It is *not* the reason we're struggling here.) This has been seen before, in another guise: #15244. And we have
```
{ Note [Do not add duplicate quantified instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this (#15244):
f :: (C g, D g) => ....
class S g => C g where ...
class S g => D g where ...
class (forall a. Eq a => Eq (g a)) => S g where ...
Then in f's RHS there are two identical quantified constraints
available, one via the superclasses of C and one via the superclasses
of D. The two are identical, and it seems wrong to reject the program
because of that. But without doing duplicateelimination we will have
two matching QCInsts when we try to solve constraints arising from f's
RHS.
The simplest thing is simply to eliminate duplicates, which we do here.
}
```
which is duly implemented. However, here, we don't have duplicates  we have nearduplicates, which are not caught by the simple (`tcEqType`) check.
I wonder if the way forward is to really try to "solve" quantified instances. That is, before labeling them inert, we try to interact them with inerts. Then, we might discover that one constraint is implied by another, which will get rid of this problem (and replace that Note).https://gitlab.haskell.org/ghc/ghc//issues/17737Recursive superclass check is defeated by quantified constraints20200310T14:21:59ZRichard Eisenbergrae@richarde.devRecursive superclass check is defeated by quantified constraintsThis is accepted:
```hs
{# LANGUAGE QuantifiedConstraints, KindSignatures, ConstraintKinds #}
module Bug where
import Data.Kind
class ((() :: Constraint) => C a) => C a
```
The vacuous constraint `()` hides the recursive superclass `C a`. Note that I do not have `RecursiveSuperclasses` enabled.
The culprit is `TcTyDecls.checkClassCycles`.
This is not a "real" bug report, in that I found the problem only by reading the source code, not by observing the misbehavior. Still, it shouldn't be hard to fix. Should we just look through quantified constraints always?This is accepted:
```hs
{# LANGUAGE QuantifiedConstraints, KindSignatures, ConstraintKinds #}
module Bug where
import Data.Kind
class ((() :: Constraint) => C a) => C a
```
The vacuous constraint `()` hides the recursive superclass `C a`. Note that I do not have `RecursiveSuperclasses` enabled.
The culprit is `TcTyDecls.checkClassCycles`.
This is not a "real" bug report, in that I found the problem only by reading the source code, not by observing the misbehavior. Still, it shouldn't be hard to fix. Should we just look through quantified constraints always?Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/17790`case` needn't instantiate its scrutinee20200205T15:31:19ZRichard Eisenbergrae@richarde.dev`case` needn't instantiate its scrutineeConsider
```hs
foo = case id of id' > (id' 'x', id' True)
```
Should this be accepted or rejected? GHC currently rejects. But simply by changing [this line](https://gitlab.haskell.org/ghc/ghc/blob/4bada77d5882974514d85d4bd0fd4e1801dad755/compiler/typecheck/TcExpr.hs#L528) to use `tcInferSigma` instead of `tcInferRho`, the program is accepted. (That's really it! Try it at home!)
Should we make this change? It makes our language more expressive. It also gets us closer to the Platonic ideal of a HindleyMilner language design, in that users should never have to think about instantiation or generalization. And ML does it. If I write
```ml
let ex = match fun x > x with
 f > (f 'x', f true)
```
then `ocamlc` accepts without complaint. Actually, this ML example is even more interesting: not only does it *preserve* the polymorphism in the scrutinee, it actually *generalizes*. Really, if Damas and Milner had been examining a language with `case`, they would have said that we need generalization at `let` and at `case`.
Of course, we could use `tcInferSigma` (enabling the Haskell example) but not to generalization. That means that `foo` would be accepted, but this `bar` would be rejected:
```hs
bar = case \x > x of id' > (id' 'x', id' True)
```
That's a bit of a shame.
This ticket is to track this small design decision.Consider
```hs
foo = case id of id' > (id' 'x', id' True)
```
Should this be accepted or rejected? GHC currently rejects. But simply by changing [this line](https://gitlab.haskell.org/ghc/ghc/blob/4bada77d5882974514d85d4bd0fd4e1801dad755/compiler/typecheck/TcExpr.hs#L528) to use `tcInferSigma` instead of `tcInferRho`, the program is accepted. (That's really it! Try it at home!)
Should we make this change? It makes our language more expressive. It also gets us closer to the Platonic ideal of a HindleyMilner language design, in that users should never have to think about instantiation or generalization. And ML does it. If I write
```ml
let ex = match fun x > x with
 f > (f 'x', f true)
```
then `ocamlc` accepts without complaint. Actually, this ML example is even more interesting: not only does it *preserve* the polymorphism in the scrutinee, it actually *generalizes*. Really, if Damas and Milner had been examining a language with `case`, they would have said that we need generalization at `let` and at `case`.
Of course, we could use `tcInferSigma` (enabling the Haskell example) but not to generalization. That means that `foo` would be accepted, but this `bar` would be rejected:
```hs
bar = case \x > x of id' > (id' 'x', id' True)
```
That's a bit of a shame.
This ticket is to track this small design decision.https://gitlab.haskell.org/ghc/ghc//issues/17934Consider using specificity to disambiguate quantified constraints20210221T15:37:18ZRichard Eisenbergrae@richarde.devConsider using specificity to disambiguate quantified constraints**Summary:** Currently, quantified constraints shadow global instances. This ticket proposes to use specificity (in the sense used by overlapping instances) instead of shadowing.
**Motivation**
This looks like a sensible way of having a datatype that can store something of a type that supports some class interface:
```haskell
data Some (c :: Type > Constraint) where
Some :: c a => a > Some c
```
But now I want to write a `Show` instance. I can do this only when the existential `a` supports `Show`. But I don't wish to require that `c ~ Show`  maybe `c a` implies `Show a`. So I write this:
```haskell
instance (forall x . c x => Show x) => Show (Some c) where
showsPrec n (Some a) = showsPrec n a
```
But now this fails. The problem is that the instance gets expanded to
```haskell
instance (forall x . c x => Show x) => Show (Some c) where
showsPrec n (Some a) = showsPrec n a
show = $dmshow
```
where `$dmshow :: Show a => a > String` is the default method implementation for `show`. When typechecking this method, GHC needs to satisfy `Show (Some c)`. The context includes two possibilities: the quantified constraint, and the toplevel instance declaration. Because local instances (= quantified constraints) shadow global ones, we use the first. So we reduce `[W] Show (Some c)` to `[W] c (Some c)`, which cannot be solved, leading to disaster.
This example first came to light in https://gitlab.haskell.org/ghc/ghc/issues/16502#note_253501, where it was copied from #17794.
Taking this new approach will likely fix #16502 and allow the original program in #17202 to be accepted. See also https://gitlab.haskell.org/ghc/ghc/issues/16502#note_253501 and https://gitlab.haskell.org/ghc/ghc/issues/16502#note_259055 for more test cases.
**Background**:
The current instance lookup (as documented [here](https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#instancelookup)) works as follows to solve a `[W] C T` constraint (for some class `C` and type `T`).
1. Look for local (nonquantified) assumptions for `[G] C T`.
2. Look for local quantified constraints whose conclusions match `C T`. If exactly one matches, select the constraint. Then, check whether any quantified constraints *unify* with `C T` (allowing any variables in `C T` to be bound). If any do, abort, complaining about potential incoherence. Otherwise, reduce `[W] C T` to the premise of the quantified constraint.
3. Same as (2), but using the global instance table.
**Proposal**:
Use specificity to disambiguate.
* Let `<=spec` denote a partial order on instance heads. `C T1 <=spec C T2` iff there exists a substitution `S` such that `S(T2) = T1`  just as is used with overlapping instances today.
* Let metavariable `I` denote givens. These can be nonquantified, quantified (local), or global.
* Define `locality(I)` be a number that denotes how local `I` is. The locality of a nonquantified given is 1, of a quantified local given is 2, and of a global is 3.
* Define partial order `<=` on instances as follows:
1. If `I1 <=spec I2` and `I2 <=spec I1`, then `I1 <= I2` is `locality(I1) <= locality(I2)`.
2. If neither `I1 <=spec I2` nor `I2 <=spec I1`, then `I1 <= I2` is `locality(I1) <= locality(I2)`.
3. Otherwise, `I1 <= I2` if `I1 <=spec I2`.
Here is the proposed instance lookup procedure:
1. Collect all givens `I` (of all localities) that match a target. Call this set `Is`. If `Is` is empty, fail.
2. Let `I0` be the minimum element of `Is` with respect to `<=`. (Consider `Is` to be setlike, discarding duplicates.) If `I0` is not defined, fail.
3. Let `Is'` be the set `Is` excluding `I0`. Case on the locality of `I0`:
* `locality(I0) = 1`: Succeed with `I0` (skipping last check, below).
* `locality(I0) = 2`: Go on to next step if `Is'` contains only global instances. If `Is'` contains local instances, fail.
* `locality(I0) = 3`: Fail if any element in `Is'` is a local quantified instance. Go on to next step if, for every `I'` in `Is'`, either `I0` is *overlapping* or `I'` is *overlappable*.
4. Collect all givens (of all localities) that *unify* with a target, excluding those in `Is`. If `IncoherentInstances` is off and this set contains at least one instances not labeled **incoherent**, fail.
5. Succeed with `I0`.
**Discussion**:
This new algorithm is meant to replicate current behavior, except in the scenario where a global instance is more specific than a local one, in which the global instance should be selected. I have tried to capture current behavior w.r.t. incoherent and overlapping instances. In any case, if my algorithm deviates from current behavior w.r.t. incoherent or overlapping instances, this deviation is unintentional.
Another possible approach is to put local and global instances on even footing (that is, set both to have locality 2) but to allow users to explicitly label local instances as overlapping. I prefer the tiered approach above, but there's something simpler about local overlapping instances, in that it's one mechanism to think about.**Summary:** Currently, quantified constraints shadow global instances. This ticket proposes to use specificity (in the sense used by overlapping instances) instead of shadowing.
**Motivation**
This looks like a sensible way of having a datatype that can store something of a type that supports some class interface:
```haskell
data Some (c :: Type > Constraint) where
Some :: c a => a > Some c
```
But now I want to write a `Show` instance. I can do this only when the existential `a` supports `Show`. But I don't wish to require that `c ~ Show`  maybe `c a` implies `Show a`. So I write this:
```haskell
instance (forall x . c x => Show x) => Show (Some c) where
showsPrec n (Some a) = showsPrec n a
```
But now this fails. The problem is that the instance gets expanded to
```haskell
instance (forall x . c x => Show x) => Show (Some c) where
showsPrec n (Some a) = showsPrec n a
show = $dmshow
```
where `$dmshow :: Show a => a > String` is the default method implementation for `show`. When typechecking this method, GHC needs to satisfy `Show (Some c)`. The context includes two possibilities: the quantified constraint, and the toplevel instance declaration. Because local instances (= quantified constraints) shadow global ones, we use the first. So we reduce `[W] Show (Some c)` to `[W] c (Some c)`, which cannot be solved, leading to disaster.
This example first came to light in https://gitlab.haskell.org/ghc/ghc/issues/16502#note_253501, where it was copied from #17794.
Taking this new approach will likely fix #16502 and allow the original program in #17202 to be accepted. See also https://gitlab.haskell.org/ghc/ghc/issues/16502#note_253501 and https://gitlab.haskell.org/ghc/ghc/issues/16502#note_259055 for more test cases.
**Background**:
The current instance lookup (as documented [here](https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#instancelookup)) works as follows to solve a `[W] C T` constraint (for some class `C` and type `T`).
1. Look for local (nonquantified) assumptions for `[G] C T`.
2. Look for local quantified constraints whose conclusions match `C T`. If exactly one matches, select the constraint. Then, check whether any quantified constraints *unify* with `C T` (allowing any variables in `C T` to be bound). If any do, abort, complaining about potential incoherence. Otherwise, reduce `[W] C T` to the premise of the quantified constraint.
3. Same as (2), but using the global instance table.
**Proposal**:
Use specificity to disambiguate.
* Let `<=spec` denote a partial order on instance heads. `C T1 <=spec C T2` iff there exists a substitution `S` such that `S(T2) = T1`  just as is used with overlapping instances today.
* Let metavariable `I` denote givens. These can be nonquantified, quantified (local), or global.
* Define `locality(I)` be a number that denotes how local `I` is. The locality of a nonquantified given is 1, of a quantified local given is 2, and of a global is 3.
* Define partial order `<=` on instances as follows:
1. If `I1 <=spec I2` and `I2 <=spec I1`, then `I1 <= I2` is `locality(I1) <= locality(I2)`.
2. If neither `I1 <=spec I2` nor `I2 <=spec I1`, then `I1 <= I2` is `locality(I1) <= locality(I2)`.
3. Otherwise, `I1 <= I2` if `I1 <=spec I2`.
Here is the proposed instance lookup procedure:
1. Collect all givens `I` (of all localities) that match a target. Call this set `Is`. If `Is` is empty, fail.
2. Let `I0` be the minimum element of `Is` with respect to `<=`. (Consider `Is` to be setlike, discarding duplicates.) If `I0` is not defined, fail.
3. Let `Is'` be the set `Is` excluding `I0`. Case on the locality of `I0`:
* `locality(I0) = 1`: Succeed with `I0` (skipping last check, below).
* `locality(I0) = 2`: Go on to next step if `Is'` contains only global instances. If `Is'` contains local instances, fail.
* `locality(I0) = 3`: Fail if any element in `Is'` is a local quantified instance. Go on to next step if, for every `I'` in `Is'`, either `I0` is *overlapping* or `I'` is *overlappable*.
4. Collect all givens (of all localities) that *unify* with a target, excluding those in `Is`. If `IncoherentInstances` is off and this set contains at least one instances not labeled **incoherent**, fail.
5. Succeed with `I0`.
**Discussion**:
This new algorithm is meant to replicate current behavior, except in the scenario where a global instance is more specific than a local one, in which the global instance should be selected. I have tried to capture current behavior w.r.t. incoherent and overlapping instances. In any case, if my algorithm deviates from current behavior w.r.t. incoherent or overlapping instances, this deviation is unintentional.
Another possible approach is to put local and global instances on even footing (that is, set both to have locality 2) but to allow users to explicitly label local instances as overlapping. I prefer the tiered approach above, but there's something simpler about local overlapping instances, in that it's one mechanism to think about.https://gitlab.haskell.org/ghc/ghc//issues/18007GHCi infers toogeneral type when patternmatching on existential GADT20200408T23:12:25Zinfinity0GHCi infers toogeneral type when patternmatching on existential GADTRun the following in ghci, I tested with version 8.8.3:
<summary>
`ghci ghciscript Test.hs`
<details>
```haskell
:set XGADTs
:set XScopedTypeVariables
 standard GADT with restricted type param
data X a where X :: X Int; XB :: X Bool
 =============================================================================
 standard ADT with full type params
data Pair0 a b t = Pair0 (a t) (b t)
Pair0 X x < pure (Pair0 X [])
:t x
 x :: [Int] as expected
x /= [10]
 True
 as expected, type inference matches x with [10]
 =============================================================================
 existential ADT, same as DSum from Data.Dependent.Sum
data Pair a b = forall t. Pair (a t) (b t)
 same results with this equivalent GADTsyntax definition:
 data Pair a b where Pair :: a t > b t > Pair a b
Pair X x < pure (Pair X [])
x /= [10]
 somehow, type inference fails to match x with [10]
 • Couldn't match expected type ‘x’ with actual type ‘Integer’
:t x
 x :: [t] but it should be
 x :: [Int] because of the Pair X

Pair X (x :: [Int]) < pure (Pair X [])
x /= [10]
 True
 giving an explicit type signature fixes inference

Pair X x < pure (Pair X [0])
x /= [10]
 True
 giving an explicit value [0] also fixes inference

:{
test :: IO ()
test = do
Pair X x < pure (Pair X [])
print (x /= [10])
:}
test
 True
 putting the code inside a function, also fixes inference??
:{
test1 :: IO (Pair X [])
test1 = pure (Pair X [])
test2 :: Pair X [] > IO ()
test2 (Pair X x) = print (x /= [10])
:}
test1 >>= test2
 True
 separating the functions also works, and we never hint x's type
```
</details>
</summary>
I think this is different from #2206 and #14065 since the error message here is a pretty generic "Couldn't match type" rather than the GADTspecific error messages in those tickets ("GADT pattern match with nonrigid result type", "untouchable inside the constraints"), and it only affects GHCi.
Run the following in ghci, I tested with version 8.8.3:
<summary>
`ghci ghciscript Test.hs`
<details>
```haskell
:set XGADTs
:set XScopedTypeVariables
 standard GADT with restricted type param
data X a where X :: X Int; XB :: X Bool
 =============================================================================
 standard ADT with full type params
data Pair0 a b t = Pair0 (a t) (b t)
Pair0 X x < pure (Pair0 X [])
:t x
 x :: [Int] as expected
x /= [10]
 True
 as expected, type inference matches x with [10]
 =============================================================================
 existential ADT, same as DSum from Data.Dependent.Sum
data Pair a b = forall t. Pair (a t) (b t)
 same results with this equivalent GADTsyntax definition:
 data Pair a b where Pair :: a t > b t > Pair a b
Pair X x < pure (Pair X [])
x /= [10]
 somehow, type inference fails to match x with [10]
 • Couldn't match expected type ‘x’ with actual type ‘Integer’
:t x
 x :: [t] but it should be
 x :: [Int] because of the Pair X

Pair X (x :: [Int]) < pure (Pair X [])
x /= [10]
 True
 giving an explicit type signature fixes inference

Pair X x < pure (Pair X [0])
x /= [10]
 True
 giving an explicit value [0] also fixes inference

:{
test :: IO ()
test = do
Pair X x < pure (Pair X [])
print (x /= [10])
:}
test
 True
 putting the code inside a function, also fixes inference??
:{
test1 :: IO (Pair X [])
test1 = pure (Pair X [])
test2 :: Pair X [] > IO ()
test2 (Pair X x) = print (x /= [10])
:}
test1 >>= test2
 True
 separating the functions also works, and we never hint x's type
```
</details>
</summary>
I think this is different from #2206 and #14065 since the error message here is a pretty generic "Couldn't match type" rather than the GADTspecific error messages in those tickets ("GADT pattern match with nonrigid result type", "untouchable inside the constraints"), and it only affects GHCi.
https://gitlab.haskell.org/ghc/ghc//issues/18062A cast might get in the way of instantiation20200427T10:20:56ZSimon Peyton JonesA cast might get in the way of instantiationSuppose we have a type signature `f :: forall a. Eq a => blah`, and it somehow kindchecks to
```
forall a. ((Eq a => Blah) > co)
```
In principle this can happen:
```
tc_hs_type mode (HsQualTy { hst_ctxt = ctxt, hst_body = rn_ty }) exp_kind
= do { ctxt' < tc_hs_context mode ctxt
; ek < newOpenTypeKind  The body kind (result of the function) can
 be TYPE r, for any r, hence newOpenTypeKind
; ty' < tc_lhs_type mode rn_ty ek
; checkExpectedKind (unLoc rn_ty) (mkPhiTy ctxt' ty')
liftedTypeKind exp_kind }
```
That `checkExpectedKind` can add a cast.
If this happens, our instantiation mechanisms would fall over in a heap. We'd instantiate the `forall a`, but then fail to instantiate the `Eq a =>`; instead we'd unify `(Eq a => blah) > co` with the function body. Bad, bad.
This popped up when fixing #18008, when a missing zonk in `tcHsPartialSigType` was producing just such a forall (with a Refl coercion). But it seems plausible that it could happen for real.
EDIT: And it does:
```hs
{# LANGUAGE KindSignatures, TypeFamilies, DataKinds #}
module Bug where
import Data.Kind ( Type )
type family Star where
Star = Type
f :: ((Eq a => a > Bool) :: Star)
f x = x == x
```
produces
```
Bug.hs:11:1: error:
• Couldn't match kind ‘Constraint’ with ‘*’
When matching types
a0 :: *
Eq a :: Constraint
Expected type: Eq a => a > Bool
Actual type: a0 > Bool
• The equation(s) for ‘f’ have one argument,
but its type ‘Eq a => a > Bool’ has none
• Relevant bindings include
f :: Eq a => a > Bool (bound at Bug.hs:11:1)

11  f x = x == x
 ^^^^^^^^^^^^
```
Solution: teach instantiation to look through casts.Suppose we have a type signature `f :: forall a. Eq a => blah`, and it somehow kindchecks to
```
forall a. ((Eq a => Blah) > co)
```
In principle this can happen:
```
tc_hs_type mode (HsQualTy { hst_ctxt = ctxt, hst_body = rn_ty }) exp_kind
= do { ctxt' < tc_hs_context mode ctxt
; ek < newOpenTypeKind  The body kind (result of the function) can
 be TYPE r, for any r, hence newOpenTypeKind
; ty' < tc_lhs_type mode rn_ty ek
; checkExpectedKind (unLoc rn_ty) (mkPhiTy ctxt' ty')
liftedTypeKind exp_kind }
```
That `checkExpectedKind` can add a cast.
If this happens, our instantiation mechanisms would fall over in a heap. We'd instantiate the `forall a`, but then fail to instantiate the `Eq a =>`; instead we'd unify `(Eq a => blah) > co` with the function body. Bad, bad.
This popped up when fixing #18008, when a missing zonk in `tcHsPartialSigType` was producing just such a forall (with a Refl coercion). But it seems plausible that it could happen for real.
EDIT: And it does:
```hs
{# LANGUAGE KindSignatures, TypeFamilies, DataKinds #}
module Bug where
import Data.Kind ( Type )
type family Star where
Star = Type
f :: ((Eq a => a > Bool) :: Star)
f x = x == x
```
produces
```
Bug.hs:11:1: error:
• Couldn't match kind ‘Constraint’ with ‘*’
When matching types
a0 :: *
Eq a :: Constraint
Expected type: Eq a => a > Bool
Actual type: a0 > Bool
• The equation(s) for ‘f’ have one argument,
but its type ‘Eq a => a > Bool’ has none
• Relevant bindings include
f :: Eq a => a > Bool (bound at Bug.hs:11:1)

11  f x = x == x
 ^^^^^^^^^^^^
```
Solution: teach instantiation to look through casts.https://gitlab.haskell.org/ghc/ghc//issues/18196Type synonym lost with GADTs20200518T18:35:05ZIdentical SnowflakeType synonym lost with GADTsConsider the following:
```haskell
type Joules = Double
type Grams = Double
data Unit a where
Energy :: Unit Joules
Mass :: Unit Grams
test :: Unit a > a
test Energy = _
```
GHC reports the hole as `_ :: Double`, but I expected the synonym to remain intact, i.e., that the hole would be `_ :: Joules`.Consider the following:
```haskell
type Joules = Double
type Grams = Double
data Unit a where
Energy :: Unit Joules
Mass :: Unit Grams
test :: Unit a > a
test Energy = _
```
GHC reports the hole as `_ :: Double`, but I expected the synonym to remain intact, i.e., that the hole would be `_ :: Joules`.https://gitlab.haskell.org/ghc/ghc//issues/18220Improve Coercible under foralls20200522T23:36:26ZSimon Peyton JonesImprove Coercible under forallsConsider
```
newtype Age = MkAge Int
h :: forall m. m Int > m Age
h x = coerce @(m Int) @(m Age) x
```
This fails, as it should, with
```
Couldn't match representation of type 'm Int'
with that of 'm Age'
arising from a use of 'coerce'
NB: We cannot know what roles the parameters to 'm' have;
we must assume that the role is nominal
```
And indeed, if we have
```
type family F a
data T a = MkT (F a)
```
Then `h @T` would indeed be bogus because `T Int` and `T Age` might have very different representations.
So far so good. Now consider
```
f :: forall m. (forall p q. Coercible p q => Coercible (m p) (m q))
=> m Int > m Age
f x = coerce @(m Int) @(m Age) x
g :: forall m. (forall p q. Coercible p q => Coercible (m p) (m q))
=> (forall a. a > m Int) > (forall a. a> m Age)
g x = coerce @(forall a. a > m Int) @(forall a. a > m Age) x
```
Here `f` succeeds. It needs `[W] Coercible (m Int) (m Age)` which it can prove from the quantified constraint.
But `g` is rejected with
```
Couldn't match representation of type 'm Int'
with that of 'm Age'
arising from a use of 'coerce'
NB: We cannot know what roles the parameters to 'm' have;
we must assume that the role is nominal
In the expression:
coerce @(forall a. a > m Int) @(forall a. a > m Age) x
```
That's odd! I can easily come up with a succesful elaboration of the program. Why? We start from
```
[W] Coercible (forall a. a > m Int) (forall a. a > m Age)
===>
[W] (forall a. a > m Int) ~R# (forall a. a > m Age)
===> {make an implication constraint}
[W] forall <noev> a. () => (a > m Int) ~R# (a > m Age)
```
The `<noev>` says that we don't have a place to put valuelevel evidence. Then we decompose:
```
===>
[W] forall <noev> a. () => (m Int) ~R# (m Age)
```
and now we are stuck because there is nowhere to put the evidence.
But the solution is simple! Just float the constraint out of the implication (it does not mention the skolem `a`). I have done this in !3319, and indeed it works.
However, it doesn't solve the full problem. What we wanted `m a Int ~R# m a Age`? Now the skolem `a` would prevent the constraint floating out, and we are back to square 1

That termlevel quantified constraint `(forall p q. Coercible p q => Coercible (m p) (m q))` is really a way of saying "m's first argument has representational role". Perhaps we should seek a way of saying that more directly, and in a way we can use in coercions. Something like `Rep# m`. Then the evidence for `Rep# m` justifies decomposing a wanted constraint `m t1 ~R# m t2`.
Another alternative would be to decorate the arrow in m's kind, as we proposed in the first roles paper.
Neither seems simple. So this ticket is just recording the issue, and pointing to the MR, for posterity.

All this arose in #18148 and #18213, but is only tangentially related in the end.Consider
```
newtype Age = MkAge Int
h :: forall m. m Int > m Age
h x = coerce @(m Int) @(m Age) x
```
This fails, as it should, with
```
Couldn't match representation of type 'm Int'
with that of 'm Age'
arising from a use of 'coerce'
NB: We cannot know what roles the parameters to 'm' have;
we must assume that the role is nominal
```
And indeed, if we have
```
type family F a
data T a = MkT (F a)
```
Then `h @T` would indeed be bogus because `T Int` and `T Age` might have very different representations.
So far so good. Now consider
```
f :: forall m. (forall p q. Coercible p q => Coercible (m p) (m q))
=> m Int > m Age
f x = coerce @(m Int) @(m Age) x
g :: forall m. (forall p q. Coercible p q => Coercible (m p) (m q))
=> (forall a. a > m Int) > (forall a. a> m Age)
g x = coerce @(forall a. a > m Int) @(forall a. a > m Age) x
```
Here `f` succeeds. It needs `[W] Coercible (m Int) (m Age)` which it can prove from the quantified constraint.
But `g` is rejected with
```
Couldn't match representation of type 'm Int'
with that of 'm Age'
arising from a use of 'coerce'
NB: We cannot know what roles the parameters to 'm' have;
we must assume that the role is nominal
In the expression:
coerce @(forall a. a > m Int) @(forall a. a > m Age) x
```
That's odd! I can easily come up with a succesful elaboration of the program. Why? We start from
```
[W] Coercible (forall a. a > m Int) (forall a. a > m Age)
===>
[W] (forall a. a > m Int) ~R# (forall a. a > m Age)
===> {make an implication constraint}
[W] forall <noev> a. () => (a > m Int) ~R# (a > m Age)
```
The `<noev>` says that we don't have a place to put valuelevel evidence. Then we decompose:
```
===>
[W] forall <noev> a. () => (m Int) ~R# (m Age)
```
and now we are stuck because there is nowhere to put the evidence.
But the solution is simple! Just float the constraint out of the implication (it does not mention the skolem `a`). I have done this in !3319, and indeed it works.
However, it doesn't solve the full problem. What we wanted `m a Int ~R# m a Age`? Now the skolem `a` would prevent the constraint floating out, and we are back to square 1

That termlevel quantified constraint `(forall p q. Coercible p q => Coercible (m p) (m q))` is really a way of saying "m's first argument has representational role". Perhaps we should seek a way of saying that more directly, and in a way we can use in coercions. Something like `Rep# m`. Then the evidence for `Rep# m` justifies decomposing a wanted constraint `m t1 ~R# m t2`.
Another alternative would be to decorate the arrow in m's kind, as we proposed in the first roles paper.
Neither seems simple. So this ticket is just recording the issue, and pointing to the MR, for posterity.

All this arose in #18148 and #18213, but is only tangentially related in the end.https://gitlab.haskell.org/ghc/ghc//issues/18295Outdated commentary in solveNestedImplications?20200604T15:36:21ZRichard Eisenbergrae@richarde.devOutdated commentary in solveNestedImplications?`GHC.Tc.Solver.solveNestedImplications` looks like this:
```hs
solveNestedImplications :: Bag Implication
> TcS (Cts, Bag Implication)
 Precondition: the TcS inerts may contain unsolved simples which have
 to be converted to givens before we go inside a nested implication.
solveNestedImplications implics
 isEmptyBag implics
= return (emptyBag, emptyBag)
 otherwise
= do { traceTcS "solveNestedImplications starting {" empty
; (floated_eqs_s, unsolved_implics) < mapAndUnzipBagM solveImplication implics
; let floated_eqs = concatBag floated_eqs_s
 ... and we are back in the original TcS inerts
 Notice that the original includes the _insoluble_simples so it was safe to ignore
 them in the beginning of this function.
; traceTcS "solveNestedImplications end }" $
vcat [ text "all floated_eqs =" <+> ppr floated_eqs
, text "unsolved_implics =" <+> ppr unsolved_implics ]
; return (floated_eqs, catBagMaybes unsolved_implics) }
```
I believe that both the `Precondition:` and the `... and we are back` comments are out of date. If they are not, they should be clarified, as I have no idea what they mean.
Also:
```hs
solveImplication :: Implication  Wanted
> TcS (Cts,  All wanted or derived floated equalities: var = type
Maybe Implication)  Simplified implication (empty or singleton)
 Precondition: The TcS monad contains an empty worklist and givenonly inerts
 which after trying to solve this implication we must restore to their original value
```
The emptyworklist precondition seems reasonable, but the "givenonly inerts" bit is as mysterious as (and sounds quite related to) the previous problem.
@simonpj help?`GHC.Tc.Solver.solveNestedImplications` looks like this:
```hs
solveNestedImplications :: Bag Implication
> TcS (Cts, Bag Implication)
 Precondition: the TcS inerts may contain unsolved simples which have
 to be converted to givens before we go inside a nested implication.
solveNestedImplications implics
 isEmptyBag implics
= return (emptyBag, emptyBag)
 otherwise
= do { traceTcS "solveNestedImplications starting {" empty
; (floated_eqs_s, unsolved_implics) < mapAndUnzipBagM solveImplication implics
; let floated_eqs = concatBag floated_eqs_s
 ... and we are back in the original TcS inerts
 Notice that the original includes the _insoluble_simples so it was safe to ignore
 them in the beginning of this function.
; traceTcS "solveNestedImplications end }" $
vcat [ text "all floated_eqs =" <+> ppr floated_eqs
, text "unsolved_implics =" <+> ppr unsolved_implics ]
; return (floated_eqs, catBagMaybes unsolved_implics) }
```
I believe that both the `Precondition:` and the `... and we are back` comments are out of date. If they are not, they should be clarified, as I have no idea what they mean.
Also:
```hs
solveImplication :: Implication  Wanted
> TcS (Cts,  All wanted or derived floated equalities: var = type
Maybe Implication)  Simplified implication (empty or singleton)
 Precondition: The TcS monad contains an empty worklist and givenonly inerts
 which after trying to solve this implication we must restore to their original value
```
The emptyworklist precondition seems reasonable, but the "givenonly inerts" bit is as mysterious as (and sounds quite related to) the previous problem.
@simonpj help?https://gitlab.haskell.org/ghc/ghc//issues/18308Order of StandaloneKindSignatures and CUSKs extensions significant20210331T15:14:45ZBjörn HegerforsOrder of StandaloneKindSignatures and CUSKs extensions significant## Summary
I have some code that compiles without the `StandaloneKindSignatures` extension, does not compile with it, but does compile again if I also add the `CUSKs` extension _after_ `StandaloneKindSignatures`. However, if I place the `CUSKs` extension _before_ `StandaloneKindSignatures`, then the code doesn't compile.
I'm not sure if I can avoid a CUSK in this case either, because it revolves around an associated type family, which to my understanding standalone kind signatures cannot (yet) be written for.
I generally try to keep my extensions arranged alphabetically, which is unfortunate in this case. But that's not at all a big worry. For now I can put `CUSKs` after `StandaloneKindSignatures` as a workaround.
## Steps to reproduce
Boiling it down to a minimal demonstrative case, this compiles:
```haskell
{# LANGUAGE MultiParamTypeClasses #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE TypeInType #}
{# LANGUAGE StandaloneKindSignatures #}
{# LANGUAGE CUSKs #}
import Data.Kind (Type)
import Data.Proxy (Proxy)
class Cls where
type Fam (k :: Type) (a :: k) :: Type
mtd :: Proxy k > Proxy (a :: k) > Fam k a > Int
```
but this doesn't:
```haskell
{# LANGUAGE MultiParamTypeClasses #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE TypeInType #}
{# LANGUAGE CUSKs #}
{# LANGUAGE StandaloneKindSignatures #}
import Data.Kind (Type)
import Data.Proxy (Proxy)
class Cls where
type Fam (k :: Type) (a :: k) :: Type
mtd :: Proxy k > Proxy (a :: k) > Fam k a > Int
```
## Expected behavior
I would expect both of the above to compile.
I should also note that it's not very clear to me what it is about the type signature for `mtd` that makes it problematic. The part that is sensitive here is the `(a :: k)` kind annotation. Whether I instead put that annotation in a `forall` makes no difference. If I simply remove the kind annotation for `a`, and let it be inferred, the code compiles regardless of which of `StandaloneKindSignatures` and `CUSKs` are enabled (and in which order). I don't know if this part behaves as expected or not.
## Environment
* GHC version used: 8.10.1## Summary
I have some code that compiles without the `StandaloneKindSignatures` extension, does not compile with it, but does compile again if I also add the `CUSKs` extension _after_ `StandaloneKindSignatures`. However, if I place the `CUSKs` extension _before_ `StandaloneKindSignatures`, then the code doesn't compile.
I'm not sure if I can avoid a CUSK in this case either, because it revolves around an associated type family, which to my understanding standalone kind signatures cannot (yet) be written for.
I generally try to keep my extensions arranged alphabetically, which is unfortunate in this case. But that's not at all a big worry. For now I can put `CUSKs` after `StandaloneKindSignatures` as a workaround.
## Steps to reproduce
Boiling it down to a minimal demonstrative case, this compiles:
```haskell
{# LANGUAGE MultiParamTypeClasses #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE TypeInType #}
{# LANGUAGE StandaloneKindSignatures #}
{# LANGUAGE CUSKs #}
import Data.Kind (Type)
import Data.Proxy (Proxy)
class Cls where
type Fam (k :: Type) (a :: k) :: Type
mtd :: Proxy k > Proxy (a :: k) > Fam k a > Int
```
but this doesn't:
```haskell
{# LANGUAGE MultiParamTypeClasses #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE TypeInType #}
{# LANGUAGE CUSKs #}
{# LANGUAGE StandaloneKindSignatures #}
import Data.Kind (Type)
import Data.Proxy (Proxy)
class Cls where
type Fam (k :: Type) (a :: k) :: Type
mtd :: Proxy k > Proxy (a :: k) > Fam k a > Int
```
## Expected behavior
I would expect both of the above to compile.
I should also note that it's not very clear to me what it is about the type signature for `mtd` that makes it problematic. The part that is sensitive here is the `(a :: k)` kind annotation. Whether I instead put that annotation in a `forall` makes no difference. If I simply remove the kind annotation for `a`, and let it be inferred, the code compiles regardless of which of `StandaloneKindSignatures` and `CUSKs` are enabled (and in which order). I don't know if this part behaves as expected or not.
## Environment
* GHC version used: 8.10.1https://gitlab.haskell.org/ghc/ghc//issues/18311Record update is overrestrictive20201005T09:00:11ZSimon Peyton JonesRecord update is overrestrictiveConsider
```
type family F a
type instance F Int = Int
type instance F Bool = Int
data T a = MkT { x :: F a, y :: a }
foo1 :: T Int > T Bool
foo1 (MkT { x = x }) = MkT { x = x, y = True}
foo2 :: T Int > T Bool
foo2 t = t { y = True }
```
`foo1` typechecks fine, but `foo2` complains
```
Foo.hs:16:10: error:
• Couldn't match type ‘Int’ with ‘Bool’
Expected type: T Bool
Actual type: T Int
• In the expression: t {y = True}
In an equation for ‘foo2’: foo2 t = t {y = True}
```
This is bogus. `foo2` should be fine  precisely because `foo1` is.
The offending code is in the `RecordUpd` case of `GHc.Tc.Gen.Expr.tcExpr`. See this comment
```
 STEP 4 Note [Type of a record update]
 Figure out types for the scrutinee and result
 Both are of form (T a b c), with fresh type variables, but with
 common variables where the scrutinee and result must have the same type
 These are variables that appear in *any* arg of *any* of the
 relevant constructors *except* in the updated fields
```
With the advent of type families "appearing in" a type is not the same as being fixed by it.
Not hard to fix; might even lead to less code!Consider
```
type family F a
type instance F Int = Int
type instance F Bool = Int
data T a = MkT { x :: F a, y :: a }
foo1 :: T Int > T Bool
foo1 (MkT { x = x }) = MkT { x = x, y = True}
foo2 :: T Int > T Bool
foo2 t = t { y = True }
```
`foo1` typechecks fine, but `foo2` complains
```
Foo.hs:16:10: error:
• Couldn't match type ‘Int’ with ‘Bool’
Expected type: T Bool
Actual type: T Int
• In the expression: t {y = True}
In an equation for ‘foo2’: foo2 t = t {y = True}
```
This is bogus. `foo2` should be fine  precisely because `foo1` is.
The offending code is in the `RecordUpd` case of `GHc.Tc.Gen.Expr.tcExpr`. See this comment
```
 STEP 4 Note [Type of a record update]
 Figure out types for the scrutinee and result
 Both are of form (T a b c), with fresh type variables, but with
 common variables where the scrutinee and result must have the same type
 These are variables that appear in *any* arg of *any* of the
 relevant constructors *except* in the updated fields
```
With the advent of type families "appearing in" a type is not the same as being fixed by it.
Not hard to fix; might even lead to less code!https://gitlab.haskell.org/ghc/ghc//issues/18406Functional dependency should constrain local inferred type, but does not20200720T13:58:34ZRichard Eisenbergrae@richarde.devFunctional dependency should constrain local inferred type, but does notIf I compile
```hs
{# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #}
module Bug where
class C a b  a > b where
op :: a > a
foo :: C a b => a > b > a
foo x y = blah x
where
blah z = [x,z] `seq` op z
```
with `ddumptc fprinttypecheckerelaboration fprintexplicitforalls`, I get
```
==================== Typechecker ====================
AbsBinds [a_apDT, b_apDU] [$dC_apDW]
{Exports: [foo <= foo_apDV
wrap: <>]
Exported types: foo :: forall a b. C a b => a > b > a
[LclId]
Binds: foo_apDV x_apD6 y_apD7
= blah_apD8 @ b_apDU $dC_apEm x_apD6
where
AbsBinds [b_apE7] [$dC_apEd]
{Exports: [blah_apD8 <= blah_apEb
wrap: <>]
Exported types: blah_apD8
:: forall {b}. C a_apDT b => a_apDT > a_apDT
[LclId]
Binds: blah_apD8 z_apD9
= [x_apD6, z_apD9] `seq` op @ a_apDT @ b_apE7 $dC_apE8 z_apD9
Evidence: [EvBinds{[W] $dC_apE8 = $dC_apEd}]}
Evidence: [EvBinds{[W] $dC_apEm = $dC_apDW}]}
```
Note that the local `blah` gets type `forall {b}. C a b => a > a`. Why quantify `b` locally? There is no reason to. There is no great harm either, but a patch I'm working on (https://gitlab.haskell.org/ghc/ghc//tree/wip/derivedrefactor) gets annoyed when this condition (which happens in the wild, in `Text.Parsec.Perm`) causes `[G] C a b1` and `[G] C a b2` to both be in scope with no relationship between `b1` and `b2`.
Will fix in ongoing work.If I compile
```hs
{# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #}
module Bug where
class C a b  a > b where
op :: a > a
foo :: C a b => a > b > a
foo x y = blah x
where
blah z = [x,z] `seq` op z
```
with `ddumptc fprinttypecheckerelaboration fprintexplicitforalls`, I get
```
==================== Typechecker ====================
AbsBinds [a_apDT, b_apDU] [$dC_apDW]
{Exports: [foo <= foo_apDV
wrap: <>]
Exported types: foo :: forall a b. C a b => a > b > a
[LclId]
Binds: foo_apDV x_apD6 y_apD7
= blah_apD8 @ b_apDU $dC_apEm x_apD6
where
AbsBinds [b_apE7] [$dC_apEd]
{Exports: [blah_apD8 <= blah_apEb
wrap: <>]
Exported types: blah_apD8
:: forall {b}. C a_apDT b => a_apDT > a_apDT
[LclId]
Binds: blah_apD8 z_apD9
= [x_apD6, z_apD9] `seq` op @ a_apDT @ b_apE7 $dC_apE8 z_apD9
Evidence: [EvBinds{[W] $dC_apE8 = $dC_apEd}]}
Evidence: [EvBinds{[W] $dC_apEm = $dC_apDW}]}
```
Note that the local `blah` gets type `forall {b}. C a b => a > a`. Why quantify `b` locally? There is no reason to. There is no great harm either, but a patch I'm working on (https://gitlab.haskell.org/ghc/ghc//tree/wip/derivedrefactor) gets annoyed when this condition (which happens in the wild, in `Text.Parsec.Perm`) causes `[G] C a b1` and `[G] C a b2` to both be in scope with no relationship between `b1` and `b2`.
Will fix in ongoing work.https://gitlab.haskell.org/ghc/ghc//issues/18413Suboptimal constraint solving20210329T08:49:08ZSimon Peyton JonesSuboptimal constraint solvingHere a summary of `ddumptctrace` for this program (part of test T12427a)
```
data T where
T1 :: a > ((forall b. [b]>[b]) > Int) > T
h11 y = case y of T1 _ v > v
```
I see this sequence
```
{co_awA} {0}:: ((forall b. [b] > [b]) > Int)
~# p_awz[tau:1] (CNonCanonical)
==> Hetero equality gives rise to kind equality
inert: {co_awG} :: p_awz[tau:1] ~# ((forall b. [b] > [b]) > Int > (TYPE {co_awF})_N)
work item: {co_awF} :: 'GHC.Types.LiftedRep ~# p_awy[tau:1]
co_awA := Sym ({co_awG} ; Sym (GRefl nominal ((forall b.[b] > [b]) > Int)
(TYPE {co_awF})_N))
==> Swap awF, kick out awG
work item: {co_awG} :: p_awz[tau:1] ~# ((forall b. [b] > [b]) > Int > (TYPE {co_awF})_N)
inert (because p_awy is untouchable):
{co_awH} :: p_awy[tau:1] ~# 'GHC.Types.LiftedRep
co_awF := Sym co_awH
==> flatten awG (strange double GRefl)
inert: {co_awH} :: p_awy[tau:1] ~# 'GHC.Types.LiftedRep
inert: {co_awI} :: p_awz[tau:1] ~# ((forall b. [b] > [b]) > Int > (TYPE (Sym {co_awH}))_N)
co_awG := {co_awI} ; (Sym (GRefl nominal ((forall b. [b] > [b]) > Int)
(TYPE (Sym {co_awH}))_N)
; GRefl nominal ((forall b. [b] > [b]) > Int)
(TYPE {co_awF})_N)
at this point we also make a derived shadow of awI, for some reason.
Solving stops here, but we float out awI, and awH, and then have another go
work: {co_awH} :: p_awy[tau:1] ~# 'GHC.Types.LiftedRep
work: {co_awI} :: p_awz[tau:1] ~# ((forall b. [b] > [b]) > Int > (TYPE (Sym {co_awH}))_N)
==> flatten awI (why?)
work: {co_awH} :: p_awy[tau:1] ~# 'GHC.Types.LiftedRep
inert: {co_awJ} :: p_awz[tau:1] ~# ((forall b. [b] > [b]) > Int > (TYPE (Sym {co_awH}))_N)
co_awI := {co_awJ} ; (Sym (GRefl nominal ((forall b. [b] > [b]) > Int)
(TYPE (Sym {co_awH}))_N) ; GRefl nominal ((forall b. [b] > [b])
> Int)
(TYPE (Sym {co_awH}))_N)
==> solve awH: p_awy := LiftedRep, kick out awJ
{co_awJ} :: p_awz[tau:1] ~# ((forall b. [b] > [b]) > Int > (TYPE (Sym {co_awH}))_N)
==> flatten awJ
co_awJ := {co_awK} ; GRefl nominal ((forall b. [b] > [b]) > Int)
(TYPE (Sym {co_awH}))_N
{co_awK} :: p_awz[tau:1] ~# ((forall b. [b] > [b]) > Int)
```
This seems like we are doing too much work, esp the double GRefls. Why did awI get flattened?
It's not a disaster, but pretty heavy handed.Here a summary of `ddumptctrace` for this program (part of test T12427a)
```
data T where
T1 :: a > ((forall b. [b]>[b]) > Int) > T
h11 y = case y of T1 _ v > v
```
I see this sequence
```
{co_awA} {0}:: ((forall b. [b] > [b]) > Int)
~# p_awz[tau:1] (CNonCanonical)
==> Hetero equality gives rise to kind equality
inert: {co_awG} :: p_awz[tau:1] ~# ((forall b. [b] > [b]) > Int > (TYPE {co_awF})_N)
work item: {co_awF} :: 'GHC.Types.LiftedRep ~# p_awy[tau:1]
co_awA := Sym ({co_awG} ; Sym (GRefl nominal ((forall b.[b] > [b]) > Int)
(TYPE {co_awF})_N))
==> Swap awF, kick out awG
work item: {co_awG} :: p_awz[tau:1] ~# ((forall b. [b] > [b]) > Int > (TYPE {co_awF})_N)
inert (because p_awy is untouchable):
{co_awH} :: p_awy[tau:1] ~# 'GHC.Types.LiftedRep
co_awF := Sym co_awH
==> flatten awG (strange double GRefl)
inert: {co_awH} :: p_awy[tau:1] ~# 'GHC.Types.LiftedRep
inert: {co_awI} :: p_awz[tau:1] ~# ((forall b. [b] > [b]) > Int > (TYPE (Sym {co_awH}))_N)
co_awG := {co_awI} ; (Sym (GRefl nominal ((forall b. [b] > [b]) > Int)
(TYPE (Sym {co_awH}))_N)
; GRefl nominal ((forall b. [b] > [b]) > Int)
(TYPE {co_awF})_N)
at this point we also make a derived shadow of awI, for some reason.
Solving stops here, but we float out awI, and awH, and then have another go
work: {co_awH} :: p_awy[tau:1] ~# 'GHC.Types.LiftedRep
work: {co_awI} :: p_awz[tau:1] ~# ((forall b. [b] > [b]) > Int > (TYPE (Sym {co_awH}))_N)
==> flatten awI (why?)
work: {co_awH} :: p_awy[tau:1] ~# 'GHC.Types.LiftedRep
inert: {co_awJ} :: p_awz[tau:1] ~# ((forall b. [b] > [b]) > Int > (TYPE (Sym {co_awH}))_N)
co_awI := {co_awJ} ; (Sym (GRefl nominal ((forall b. [b] > [b]) > Int)
(TYPE (Sym {co_awH}))_N) ; GRefl nominal ((forall b. [b] > [b])
> Int)
(TYPE (Sym {co_awH}))_N)
==> solve awH: p_awy := LiftedRep, kick out awJ
{co_awJ} :: p_awz[tau:1] ~# ((forall b. [b] > [b]) > Int > (TYPE (Sym {co_awH}))_N)
==> flatten awJ
co_awJ := {co_awK} ; GRefl nominal ((forall b. [b] > [b]) > Int)
(TYPE (Sym {co_awH}))_N
{co_awK} :: p_awz[tau:1] ~# ((forall b. [b] > [b]) > Int)
```
This seems like we are doing too much work, esp the double GRefls. Why did awI get flattened?
It's not a disaster, but pretty heavy handed.Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/18456"equirecursive" type family leads to stack overflow in ghci20200717T13:59:54ZXia Liyao"equirecursive" type family leads to stack overflow in ghci## Summary
Trying to typecheck a term using a (silly) type family such that `T ~ Maybe T` leads to a stack overflow (instead of a proper type error from reaching the max reduction depth, if this is to be an error at all).
## Steps to reproduce
```
> :set XTypeFamilies XUndecidableInstances
> type family T where T = Maybe T
> :t Nothing @T
Nothing @T*** Exception: stack overflow
```
(where the exception takes a few seconds to appear)
Compare that output to this variant that immediately produces a proper type error:
```
> :t Nothing @T :: T
<interactive>:5:1 error:
...
```
## Expected behavior
Either a success (`Nothing @T` has type `Maybe T` without requiring any type conversion), or a type error instead of an internal exception.
## Environment
* GHC version used: 8.10.1## Summary
Trying to typecheck a term using a (silly) type family such that `T ~ Maybe T` leads to a stack overflow (instead of a proper type error from reaching the max reduction depth, if this is to be an error at all).
## Steps to reproduce
```
> :set XTypeFamilies XUndecidableInstances
> type family T where T = Maybe T
> :t Nothing @T
Nothing @T*** Exception: stack overflow
```
(where the exception takes a few seconds to appear)
Compare that output to this variant that immediately produces a proper type error:
```
> :t Nothing @T :: T
<interactive>:5:1 error:
...
```
## Expected behavior
Either a success (`Nothing @T` has type `Maybe T` without requiring any type conversion), or a type error instead of an internal exception.
## Environment
* GHC version used: 8.10.1https://gitlab.haskell.org/ghc/ghc//issues/18529GHC fails to infer type with FlexibleContexts20210726T12:22:00ZRichard Eisenbergrae@richarde.devGHC fails to infer type with FlexibleContextsIf I say
```hs
{# LANGUAGE MultiParamTypeClasses, FlexibleContexts #}
module Bug where
class C a b where
op :: a > b > ()
 foo :: (C a Integer) => a > ()
foo x = op x 3
```
then GHC complains that the variable `b0` in the type of `foo` is ambiguous, because it tries to produce `C a b => a > ()` as the type of `foo`. Instead, it shouldn't quantify `b`, letting it default to `Integer`.
The solution is to use `oclose` instead of `growThetaTyVars` in `decideQuantifiedTyVars`. This will respect functional dependencies, quantifying over `b` only when a fundep exists from `a` to `b`.
I will fix in ongoing work (in the `wip/derivedrefactor` branch).If I say
```hs
{# LANGUAGE MultiParamTypeClasses, FlexibleContexts #}
module Bug where
class C a b where
op :: a > b > ()
 foo :: (C a Integer) => a > ()
foo x = op x 3
```
then GHC complains that the variable `b0` in the type of `foo` is ambiguous, because it tries to produce `C a b => a > ()` as the type of `foo`. Instead, it shouldn't quantify `b`, letting it default to `Integer`.
The solution is to use `oclose` instead of `growThetaTyVars` in `decideQuantifiedTyVars`. This will respect functional dependencies, quantifying over `b` only when a fundep exists from `a` to `b`.
I will fix in ongoing work (in the `wip/derivedrefactor` branch).Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/18689Why check for fdefertypeerrors in metaTyVarUpdateOK?20201222T13:22:39ZRichard Eisenbergrae@richarde.devWhy check for fdefertypeerrors in metaTyVarUpdateOK?Function `checkTypeEq` changes its behavior depending on the presence of `fdefertypeerrors` in an obscure case around heterogeneous equalities; see the code in `go_co`. This is undocumented (in the code), and neither Simon nor I can figure out why it's done.
Task: figure this out, and either document or remove this behavior.Function `checkTypeEq` changes its behavior depending on the presence of `fdefertypeerrors` in an obscure case around heterogeneous equalities; see the code in `go_co`. This is undocumented (in the code), and neither Simon nor I can figure out why it's done.
Task: figure this out, and either document or remove this behavior.Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/18704GHC could not deduce constraint from itself20200930T21:23:04ZrybochodonezzarGHC could not deduce constraint from itself## Summary
following code:
```haskell
{# LANGUAGE GADTs, DataKinds, PolyKinds, ConstraintKinds, TypeApplications, RankNTypes, TypeFamilies, TypeOperators, MultiParamTypeClasses, UndecidableSuperClasses, FlexibleInstances, PatternSynonyms, FlexibleContexts, AllowAmbiguousTypes, ScopedTypeVariables #}
module Lib where
import GHC.Exts
import GHC.TypeLits
import Data.Proxy
data a ::: b = a ::: b
class Pair f where
type Left f :: a
type Right f :: b
instance Pair (a '::: b) where
type Left (a '::: b) = a
type Right (a '::: b) = b
class NC (x :: k)
instance NC (x :: k)
data L1 c f xs where
LC :: c x => f x > L1 c f xs > L1 c f (x ': xs)
LN :: L1 c f '[]
class (c1 (Left f), c2 (Right f)) => PairC c1 c2 f
instance (c1 x, c2 y) => PairC c1 c2 (x '::: y)
data f1 :*: f2 :: (kx ::: ky) > * where
(:*:) :: f1 x > f2 y > (f1 :*: f2) (x '::: y)
pairC :: forall c1 c2 x y e . (c1 x, c2 y) => (PairC c1 c2 (x '::: y) => e) > e
pairC e = e
type Foo t = L1 (PairC KnownSymbol NC) (Proxy :*: t)
pattern Foo :: forall s a t xs . KnownSymbol s => KnownSymbol s => Proxy s > t a > Foo t xs > Foo t (s '::: a ': xs)
pattern Foo p t xs < LC (p :*: t) xs where
Foo p t xs = pairC @KnownSymbol @NC @s @a (LC (p :*: t) xs)
```
Results in this compile error:
```
/home/ryba/ghcbug/src/Lib.hs:38:46: error:
• Could not deduce (PairC KnownSymbol NC (s '::: a))
arising from a use of ‘LC’
from the context: KnownSymbol s
bound by the signature for pattern synonym ‘Foo’
at src/Lib.hs:(37,1)(38,61)
or from: PairC KnownSymbol NC (s '::: a)
bound by a type expected by the context:
PairC KnownSymbol NC (s '::: a) =>
L1 (PairC KnownSymbol NC) (Proxy :*: t) ((s '::: a) : xs)
at src/Lib.hs:38:4561
• In the fifth argument of ‘pairC’, namely ‘(LC (p :*: t) xs)’
In the expression: pairC @KnownSymbol @NC @s @a (LC (p :*: t) xs)
In an equation for ‘Foo’:
Foo p t xs = pairC @KnownSymbol @NC @s @a (LC (p :*: t) xs)

38  Foo p t xs = pairC @KnownSymbol @NC @s @a (LC (p :*: t) xs)
 ^^^^^^^^^^^^^^^
```
Which basically boils down to "could not deduce a from a"
## Environment
* GHC version used: 8.10.2
* stack resolver=nightly20200914
Optional:
* Operating System: Ubuntu
* System Architecture: x8664## Summary
following code:
```haskell
{# LANGUAGE GADTs, DataKinds, PolyKinds, ConstraintKinds, TypeApplications, RankNTypes, TypeFamilies, TypeOperators, MultiParamTypeClasses, UndecidableSuperClasses, FlexibleInstances, PatternSynonyms, FlexibleContexts, AllowAmbiguousTypes, ScopedTypeVariables #}
module Lib where
import GHC.Exts
import GHC.TypeLits
import Data.Proxy
data a ::: b = a ::: b
class Pair f where
type Left f :: a
type Right f :: b
instance Pair (a '::: b) where
type Left (a '::: b) = a
type Right (a '::: b) = b
class NC (x :: k)
instance NC (x :: k)
data L1 c f xs where
LC :: c x => f x > L1 c f xs > L1 c f (x ': xs)
LN :: L1 c f '[]
class (c1 (Left f), c2 (Right f)) => PairC c1 c2 f
instance (c1 x, c2 y) => PairC c1 c2 (x '::: y)
data f1 :*: f2 :: (kx ::: ky) > * where
(:*:) :: f1 x > f2 y > (f1 :*: f2) (x '::: y)
pairC :: forall c1 c2 x y e . (c1 x, c2 y) => (PairC c1 c2 (x '::: y) => e) > e
pairC e = e
type Foo t = L1 (PairC KnownSymbol NC) (Proxy :*: t)
pattern Foo :: forall s a t xs . KnownSymbol s => KnownSymbol s => Proxy s > t a > Foo t xs > Foo t (s '::: a ': xs)
pattern Foo p t xs < LC (p :*: t) xs where
Foo p t xs = pairC @KnownSymbol @NC @s @a (LC (p :*: t) xs)
```
Results in this compile error:
```
/home/ryba/ghcbug/src/Lib.hs:38:46: error:
• Could not deduce (PairC KnownSymbol NC (s '::: a))
arising from a use of ‘LC’
from the context: KnownSymbol s
bound by the signature for pattern synonym ‘Foo’
at src/Lib.hs:(37,1)(38,61)
or from: PairC KnownSymbol NC (s '::: a)
bound by a type expected by the context:
PairC KnownSymbol NC (s '::: a) =>
L1 (PairC KnownSymbol NC) (Proxy :*: t) ((s '::: a) : xs)
at src/Lib.hs:38:4561
• In the fifth argument of ‘pairC’, namely ‘(LC (p :*: t) xs)’
In the expression: pairC @KnownSymbol @NC @s @a (LC (p :*: t) xs)
In an equation for ‘Foo’:
Foo p t xs = pairC @KnownSymbol @NC @s @a (LC (p :*: t) xs)

38  Foo p t xs = pairC @KnownSymbol @NC @s @a (LC (p :*: t) xs)
 ^^^^^^^^^^^^^^^
```
Which basically boils down to "could not deduce a from a"
## Environment
* GHC version used: 8.10.2
* stack resolver=nightly20200914
Optional:
* Operating System: Ubuntu
* System Architecture: x8664https://gitlab.haskell.org/ghc/ghc//issues/18738Infer multiplicity of case expression20210705T16:14:28ZArnaud SpiwackInfer multiplicity of case expression## Motivation
As it stands, the following expression
```haskell
case u of {…}
```
is always understood by the typechecker as consuming `u` with multiplicity `Many`. This was done in the first iteration of patch in order to ensure being fully compatible with regular Haskell without having to delve too much into inference issue.
This applies to case expressions and to pattern guards creating a pattern:
```haskell
 pat < u, … = …
```
here u is also consumed with multiplicity `Many`.
(In a `\case` or a function definition by equations, the multiplicity is decided by the type that it is checked against, if any. So it may be any multiplicity.)
Core is already equipped to deal with arbitrary multiplicities here.
## Proposal
These expressions should infer the appropriate multiplicity. So typechecking such a case expression should emit a multiplicity variable instead of choosing `Many` systematically.
One somewhat subtle point to keep in mind is that some patterns require that the scrutinee be consumed unrestrictedly. That's the case, for instance, of wildcard patterns (`_`). I believe that the current implementation will handle a variable for the pattern's multiplicity smoothly (see `checkManyPattern` in `GHC.Tc.Gen.Pat` ([currently](https://gitlab.haskell.org/ghc/ghc//blob/d7385f7077c6258c2a76ae51b4ea80f6fa9c7015/compiler/GHC/Tc/Gen/Pat.hs#L348349)). But it's worth doublechecking.
For pattern guard the relevant code is the `BindStmt` case of `tcGuardStmt` in `GHC.Tc.Gen.Match`.
cc @monoidal## Motivation
As it stands, the following expression
```haskell
case u of {…}
```
is always understood by the typechecker as consuming `u` with multiplicity `Many`. This was done in the first iteration of patch in order to ensure being fully compatible with regular Haskell without having to delve too much into inference issue.
This applies to case expressions and to pattern guards creating a pattern:
```haskell
 pat < u, … = …
```
here u is also consumed with multiplicity `Many`.
(In a `\case` or a function definition by equations, the multiplicity is decided by the type that it is checked against, if any. So it may be any multiplicity.)
Core is already equipped to deal with arbitrary multiplicities here.
## Proposal
These expressions should infer the appropriate multiplicity. So typechecking such a case expression should emit a multiplicity variable instead of choosing `Many` systematically.
One somewhat subtle point to keep in mind is that some patterns require that the scrutinee be consumed unrestrictedly. That's the case, for instance, of wildcard patterns (`_`). I believe that the current implementation will handle a variable for the pattern's multiplicity smoothly (see `checkManyPattern` in `GHC.Tc.Gen.Pat` ([currently](https://gitlab.haskell.org/ghc/ghc//blob/d7385f7077c6258c2a76ae51b4ea80f6fa9c7015/compiler/GHC/Tc/Gen/Pat.hs#L348349)). But it's worth doublechecking.
For pattern guard the relevant code is the `BindStmt` case of `tcGuardStmt` in `GHC.Tc.Gen.Match`.
cc @monoidalhttps://gitlab.haskell.org/ghc/ghc//issues/18739Infer multiplicity of let expression20210412T17:45:47ZArnaud SpiwackInfer multiplicity of let expression## Motivation
In a let expression `let x = rhs in u`, `x` is always bound with multiplicity `Many` (and, correspondingly, `u` is consumed with multiplicity `Many`).
This also holds of where expression `u where x = rhs`.
The situation is similar to that of case expression as in #18738 .
In #18461 , we are adding a syntax to force polymorphism, but programmers expect let expressions to know their multiplicity on their own (in particular, they expect `let x = y in u` to be the same as `u[x\y]`, but if the latter consumes `y` linearly, the former never does in the current GHC).
## Proposal
Infer the multiplicity of `let` binders instead of choosing `Many` systematically. The multiplicity would be a variable.
A small detail to pay attention to is that, in `let pat = rhs in u`, the outermost pattern of `pat` is lazy. Lazy pattern are only permissible in unrestricted patterns (one way to think about it is that the desugaring of lazy pattern is not linear).
The typechecker doesn't make this property very apparent, so we will have to be careful about it. I suppose the same issue arises in #18461 .## Motivation
In a let expression `let x = rhs in u`, `x` is always bound with multiplicity `Many` (and, correspondingly, `u` is consumed with multiplicity `Many`).
This also holds of where expression `u where x = rhs`.
The situation is similar to that of case expression as in #18738 .
In #18461 , we are adding a syntax to force polymorphism, but programmers expect let expressions to know their multiplicity on their own (in particular, they expect `let x = y in u` to be the same as `u[x\y]`, but if the latter consumes `y` linearly, the former never does in the current GHC).
## Proposal
Infer the multiplicity of `let` binders instead of choosing `Many` systematically. The multiplicity would be a variable.
A small detail to pay attention to is that, in `let pat = rhs in u`, the outermost pattern of `pat` is lazy. Lazy pattern are only permissible in unrestricted patterns (one way to think about it is that the desugaring of lazy pattern is not linear).
The typechecker doesn't make this property very apparent, so we will have to be careful about it. I suppose the same issue arises in #18461 .https://gitlab.haskell.org/ghc/ghc//issues/18758Remove NoGhcTc, allow HsType GhcTc, HsDecl GhcTc20210328T09:35:04ZVladislav ZavialovRemove NoGhcTc, allow HsType GhcTc, HsDecl GhcTc## Background
Currently, we carefully avoid `HsType GhcTc` or `HsDecl GhcTc`, by means of the `NoGhcTc` type family:
```
 HsAppType (XAppTypeE p)  After typechecking: the type argument
(LHsExpr p)
(LHsWcType (NoGhcTc p))  ^ Visible type application
```
The primary reason for this is that kindchecking and desugaring of types are intertwined. We mostly work with `TcType` instead of `HsType GhcTc` because it's more convenient in some places (e.g. in `unifyKind` and `unifyType`).
## Motivation A
A better architecture would be to have similar pipelines for terms and types:
* `HsExpr GhcPs > HsExpr GhcRn > HsExpr GhcTc`
* `HsType GhcPs > HsType GhcRn > HsType GhcTc`
This would allow us to talk about e.g. `HsDecl GhcTc`. For example, when discussing #12088, there was an idea of a refactoring that would separate `tcTyClDecl` and zonking. But then we'd like the type of `tcTyClDecl` to be:
```haskell
tcTyClDecl :: LTyClDecl GhcRn > TcM (LTyClDecl GhcTc)
```
And that's not currently possible.
## Motivation B
This would facilitate fixing #15824, for instance, as we could use `HsType GhcTc` as the input to `GHC.Tc.Gen.Splice.reifyType`. This way, we would retain the `HsOpTy` and `HsAppTy` distinction.
## Partial Solution
In order to address Motivation B, we would need to properly embed coercions into `HsType GhcTc` and start using it throughout the type checker. However, that would be a very major, intrusive refactoring. Before we do that, there's a stopgap solution that could be used to address Motivation A.
Define the following `XXType` instance:
```
type instance XXType GhcTc = HsTypeTc
data HsTypeTc = HsTypeTc TcType SDoc
```
Then `HsType GhcTc` would only ever use `XHsType (HsTypeTc ty doc)`. The fields are as follows:
* `TcType` is the kindchecked, desugared type
* `SDoc` is the result of pretty printing `HsType GhcRn`, before parentheses and infix operators were discarded
This is sufficient to let us talk about `HsType GhcTc` and `HsDecl GhcTc`, and remove the `NoGhcTc` type family.
## Full Solution
The full solution would involve using `HsType GhcTc` throughout the type checker, rewriting zonking and unification to work over `HsType GhcTc`, and so on. It would address Motivation A, and also let us remove the notion of `TcType`: the type checker would work with `HsType GhcTc`, and `Type` would be only used in Core. That would be a nice improvement, as we could remove `TcTyVar` and `AnonArgFlag` (maybe something else?) from the syntax of Core.
## Completion
1. The partial solution is implemented.
I think we should start with the partial solution, so that's what this ticket is about. The full solution will require much more thought and design effort, so we can get back to it later.## Background
Currently, we carefully avoid `HsType GhcTc` or `HsDecl GhcTc`, by means of the `NoGhcTc` type family:
```
 HsAppType (XAppTypeE p)  After typechecking: the type argument
(LHsExpr p)
(LHsWcType (NoGhcTc p))  ^ Visible type application
```
The primary reason for this is that kindchecking and desugaring of types are intertwined. We mostly work with `TcType` instead of `HsType GhcTc` because it's more convenient in some places (e.g. in `unifyKind` and `unifyType`).
## Motivation A
A better architecture would be to have similar pipelines for terms and types:
* `HsExpr GhcPs > HsExpr GhcRn > HsExpr GhcTc`
* `HsType GhcPs > HsType GhcRn > HsType GhcTc`
This would allow us to talk about e.g. `HsDecl GhcTc`. For example, when discussing #12088, there was an idea of a refactoring that would separate `tcTyClDecl` and zonking. But then we'd like the type of `tcTyClDecl` to be:
```haskell
tcTyClDecl :: LTyClDecl GhcRn > TcM (LTyClDecl GhcTc)
```
And that's not currently possible.
## Motivation B
This would facilitate fixing #15824, for instance, as we could use `HsType GhcTc` as the input to `GHC.Tc.Gen.Splice.reifyType`. This way, we would retain the `HsOpTy` and `HsAppTy` distinction.
## Partial Solution
In order to address Motivation B, we would need to properly embed coercions into `HsType GhcTc` and start using it throughout the type checker. However, that would be a very major, intrusive refactoring. Before we do that, there's a stopgap solution that could be used to address Motivation A.
Define the following `XXType` instance:
```
type instance XXType GhcTc = HsTypeTc
data HsTypeTc = HsTypeTc TcType SDoc
```
Then `HsType GhcTc` would only ever use `XHsType (HsTypeTc ty doc)`. The fields are as follows:
* `TcType` is the kindchecked, desugared type
* `SDoc` is the result of pretty printing `HsType GhcRn`, before parentheses and infix operators were discarded
This is sufficient to let us talk about `HsType GhcTc` and `HsDecl GhcTc`, and remove the `NoGhcTc` type family.
## Full Solution
The full solution would involve using `HsType GhcTc` throughout the type checker, rewriting zonking and unification to work over `HsType GhcTc`, and so on. It would address Motivation A, and also let us remove the notion of `TcType`: the type checker would work with `HsType GhcTc`, and `Type` would be only used in Core. That would be a nice improvement, as we could remove `TcTyVar` and `AnonArgFlag` (maybe something else?) from the syntax of Core.
## Completion
1. The partial solution is implemented.
I think we should start with the partial solution, so that's what this ticket is about. The full solution will require much more thought and design effort, so we can get back to it later.9.2.1Vladislav ZavialovVladislav Zavialovhttps://gitlab.haskell.org/ghc/ghc//issues/18802Typecheck record update via desugaring20201005T20:51:46ZSimon Peyton JonesTypecheck record update via desugaringThere are quite a few tickets relating to inadequacies of record update, including
* #18311
* #10856
* #2595
* #10808
* #3632: updating existentials if you do all of them at once
* #16501
Record update is a place where our general plan of typechecking the source syntax seems particularly hard to do. It wold be much easier (and correct by construction) to desugar (but still in HsSyn) and typecheck that.
Fortunately we now have a way to do that: our [Reengineer rebindable syntax](https://gitlab.haskell.org/ghc/ghc//issues/17582) ticket, #17582. A lot of attention is paid there to maintaining good error messages, which is the main challenge of this approach.
So this ticket is to propose: let's use the work on #17582 to solve our recordupdate tickets.There are quite a few tickets relating to inadequacies of record update, including
* #18311
* #10856
* #2595
* #10808
* #3632: updating existentials if you do all of them at once
* #16501
Record update is a place where our general plan of typechecking the source syntax seems particularly hard to do. It wold be much easier (and correct by construction) to desugar (but still in HsSyn) and typecheck that.
Fortunately we now have a way to do that: our [Reengineer rebindable syntax](https://gitlab.haskell.org/ghc/ghc//issues/17582) ticket, #17582. A lot of attention is paid there to maintaining good error messages, which is the main challenge of this approach.
So this ticket is to propose: let's use the work on #17582 to solve our recordupdate tickets.https://gitlab.haskell.org/ghc/ghc//issues/18850Instance/given overlap trips up the ambiguity check20201029T19:00:42ZRichard Eisenbergrae@richarde.devInstance/given overlap trips up the ambiguity checkThursday is a good day to abuse GHC. So I said this:
```hs
{# LANGUAGE TypeFamilies, FlexibleInstances #}
module Bug where
class IsBool bool
instance bool ~ Bool => IsBool bool
class C a
instance C Bool
f :: (C bool, IsBool bool) => ()
f = ()
```
To me, `f`'s type is unambiguous: the `IsBool bool` constraint fixes the type variable `bool` to be `Bool`. But GHC says
```
/Users/rae/temp/Bug2.hs:11:6: error:
• Could not deduce (C bool0)
from the context: (C bool, IsBool bool)
bound by the type signature for:
f :: forall bool. (C bool, IsBool bool) => ()
at /Users/rae/temp/Bug2.hs:11:632
The type variable ‘bool0’ is ambiguous
• In the ambiguity check for ‘f’
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
In the type signature: f :: (C bool, IsBool bool) => ()

11  f :: (C bool, IsBool bool) => ()
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
But maybe I'm wrong. Is the type really ambiguous? No. When I say
```hs
{# LANGUAGE TypeFamilies, FlexibleInstances, AllowAmbiguousTypes #}
module Bug where
class IsBool bool
instance bool ~ Bool => IsBool bool
class C a
instance C Bool
f :: (C bool, IsBool bool) => ()
f = ()
g = f
```
my program is accepted. I've added `AllowAmbiguousTypes` and the binding `g = f`. That binding is accepted  no type applications or other funny business. This suggests that `f`'s type is not actually ambiguous.
What's going on is an overeager instance/given overlap; see `Note [Instance and Given overlap]` in `GHC.Tc.Solver.Interact`. That Note ends with
```
All of this is disgustingly delicate, so to discourage people from writing
simplifiable class givens, we warn about signatures that contain them;
see GHC.Tc.Validity Note [Simplifiable given constraints].
```
But I don't get the warning! Even in my second program, which is errorfree. Hunting further into `GHC.Tc.Validity`, I find this code:
```hs
checkSimplifiableClassConstraint env dflags ctxt cls tys
 not (wopt Opt_WarnSimplifiableClassConstraints dflags)
= return ()
 xopt LangExt.MonoLocalBinds dflags
= return ()
 ...
```
where the `...` includes generating a warning. Of course, I *do* have `XMonoLocalBinds`, as implied by `XTypeFamilies`. What happens when I disable this (with an explicit `XNoMonoLocalBinds`)?
```
/Users/rae/temp/Bug2.hs:11:6: warning: [Wsimplifiableclassconstraints]
• The constraint ‘IsBool bool’ matches
instance (bool ~ Bool) => IsBool bool
 Defined at /Users/rae/temp/Bug2.hs:6:10
This makes type inference for inner bindings fragile;
either use MonoLocalBinds, or simplify it using the instance
• In the type signature: f :: (C bool, IsBool bool) => ()

11  f :: (C bool, IsBool bool) => ()
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
Good. The warning fires.
My conclusions:
1. My first program really ought to be accepted. The type is not ambiguous. I'm willing to concede this point to "disgustingly delicate", though, if we don't see an easy way to fix.
2. It looks the warning should fire even when `XMonoLocalBinds` is in effect. My program has no local generalization involved. How would users disable the warnings? By not writing a simplifiable Given.Thursday is a good day to abuse GHC. So I said this:
```hs
{# LANGUAGE TypeFamilies, FlexibleInstances #}
module Bug where
class IsBool bool
instance bool ~ Bool => IsBool bool
class C a
instance C Bool
f :: (C bool, IsBool bool) => ()
f = ()
```
To me, `f`'s type is unambiguous: the `IsBool bool` constraint fixes the type variable `bool` to be `Bool`. But GHC says
```
/Users/rae/temp/Bug2.hs:11:6: error:
• Could not deduce (C bool0)
from the context: (C bool, IsBool bool)
bound by the type signature for:
f :: forall bool. (C bool, IsBool bool) => ()
at /Users/rae/temp/Bug2.hs:11:632
The type variable ‘bool0’ is ambiguous
• In the ambiguity check for ‘f’
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
In the type signature: f :: (C bool, IsBool bool) => ()

11  f :: (C bool, IsBool bool) => ()
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
But maybe I'm wrong. Is the type really ambiguous? No. When I say
```hs
{# LANGUAGE TypeFamilies, FlexibleInstances, AllowAmbiguousTypes #}
module Bug where
class IsBool bool
instance bool ~ Bool => IsBool bool
class C a
instance C Bool
f :: (C bool, IsBool bool) => ()
f = ()
g = f
```
my program is accepted. I've added `AllowAmbiguousTypes` and the binding `g = f`. That binding is accepted  no type applications or other funny business. This suggests that `f`'s type is not actually ambiguous.
What's going on is an overeager instance/given overlap; see `Note [Instance and Given overlap]` in `GHC.Tc.Solver.Interact`. That Note ends with
```
All of this is disgustingly delicate, so to discourage people from writing
simplifiable class givens, we warn about signatures that contain them;
see GHC.Tc.Validity Note [Simplifiable given constraints].
```
But I don't get the warning! Even in my second program, which is errorfree. Hunting further into `GHC.Tc.Validity`, I find this code:
```hs
checkSimplifiableClassConstraint env dflags ctxt cls tys
 not (wopt Opt_WarnSimplifiableClassConstraints dflags)
= return ()
 xopt LangExt.MonoLocalBinds dflags
= return ()
 ...
```
where the `...` includes generating a warning. Of course, I *do* have `XMonoLocalBinds`, as implied by `XTypeFamilies`. What happens when I disable this (with an explicit `XNoMonoLocalBinds`)?
```
/Users/rae/temp/Bug2.hs:11:6: warning: [Wsimplifiableclassconstraints]
• The constraint ‘IsBool bool’ matches
instance (bool ~ Bool) => IsBool bool
 Defined at /Users/rae/temp/Bug2.hs:6:10
This makes type inference for inner bindings fragile;
either use MonoLocalBinds, or simplify it using the instance
• In the type signature: f :: (C bool, IsBool bool) => ()

11  f :: (C bool, IsBool bool) => ()
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
Good. The warning fires.
My conclusions:
1. My first program really ought to be accepted. The type is not ambiguous. I'm willing to concede this point to "disgustingly delicate", though, if we don't see an easy way to fix.
2. It looks the warning should fire even when `XMonoLocalBinds` is in effect. My program has no local generalization involved. How would users disable the warnings? By not writing a simplifiable Given.https://gitlab.haskell.org/ghc/ghc//issues/18851Nonconfluence in the solver20210104T22:12:36ZRichard Eisenbergrae@richarde.devNonconfluence in the solverIn #18759 (starting at https://gitlab.haskell.org/ghc/ghc//issues/18759#note_306441 and then refined in https://gitlab.haskell.org/ghc/ghc//issues/18759#note_306722, but you don't need to read that ticket to understand this one), we explored various ways of disabling the coverage condition for functional dependencies. In https://gitlab.haskell.org/ghc/ghc//issues/18759#note_307486, @simonpj asks whether these techniques can disrupt confluence.
They can. (EDIT: Furthermore, more hammering in this direction discovered nonconfluence even *without* functional dependencies. See https://gitlab.haskell.org/ghc/ghc//issues/18851#note_318471.)
Here is the example:
```hs
{# LANGUAGE FunctionalDependencies, FlexibleInstances, UndecidableInstances,
ScopedTypeVariables, TypeFamilies, TypeApplications,
FlexibleContexts, AllowAmbiguousTypes #}
module Bug where
class C a b  a > b
instance C Int b => C Int b
class IsInt int
instance int ~ Int => IsInt int
data A
instance Show A where
show _ = "A"
data B
instance Show B where
show _ = "B"
f :: forall a b c int. (Show a, Show b, Show c, C int a, C int b, C int c, IsInt int) => String
f = show (undefined :: c)
g = f @A @B
```
`g` evaluates to `"B"`. If I switch the order of the `C int a` and `C int b` constraints in the type of `f`, `g` will evaluate to `"A"`. Urgh.
(Sidenote: this file needs `AllowAmbiguousTypes`, but there are no ambiguous types here. That bug is reported as #18850.)
What's going on? When calling `f` from `g`, GHC needs to figure out how to instantiate the type variables `a`, `b`, `c`, and `int`, and GHC must find dictionaries to supply for all the class constraints. First, GHC creates unification variables `a0`, `b0`, `c0`, and `int0`. The type applications tell us `a0 := A` and `b0 := B`. Good. Then we have these constraints:
```
[W] w1 : Show A
[W] w2 : Show B
[W] w3 : Show c0
[W] w4 : C int0 A
[W] w5 : C int0 B
[W] w6 : C int0 c0
[W] w7 : IsInt int0
```
GHC processes these in the order given. `w1` and `w2` are easily despatched. `w3` doesn't make any progress at all. Neither does `w4` or `w5`. So we're then in this state:
```
worklist: [W] w6 : C int0 c0
[W] w7 : IsInt int0
inerts: [W] w3 : Show c0
[W] w4 : C int0 A
[W] w5 : C int0 B
```
We then look at `w6`. It doesn't make progress. But then GHC looks at the inerts, and sees that `w4` and `w5` have the same first argument to `C` (`int0`) as the work item `w6`. Because of the functional dependency on `C`, this means that `c0` must match the second argument to `C` in the inert. The problem is that there are *two* such inerts! GHC chooses the last one, arbitrarily. Thus, we get `c0 := B` and carry on. If the constraints were processed in a different order, we'd end up with `c0 := A`. This is classic nonconfluence.
Why have `IsInt` here? It's to slow down GHC. If we just wrote an explicit `Int` in the type signature for `f`, then GHC would eagerly solve `w4' : C Int A` and `w5' : C Int B`. When processing `w6' : C Int c0`, GHC wouldn't have any inerts to look at. Instead, it would look at the instance for `C`, which is unhelpful in this case. Indeed, moving the `IsInt int` constraint earlier (before the `C` constraints) in `f`'s type signature causes GHC to error, as it doesn't know how to instantiate `c0`, having lost the hints from the inerts. (More nonconfluence!)
What to do? I think the next step is to compare this to the [constrainthandling rules paper](https://www.researchgate.net/profile/Martin_Sulzmann/publication/213885702_Understanding_Functional_Dependencies_via_Constraint_Handling_Rules/links/09e41511297969891f000000.pdf), which proves confluence, and see whether that paper has a mistake, or where GHC violates an assumption in that paper. (Probably the latter: my instance for `C` is very naughty.)In #18759 (starting at https://gitlab.haskell.org/ghc/ghc//issues/18759#note_306441 and then refined in https://gitlab.haskell.org/ghc/ghc//issues/18759#note_306722, but you don't need to read that ticket to understand this one), we explored various ways of disabling the coverage condition for functional dependencies. In https://gitlab.haskell.org/ghc/ghc//issues/18759#note_307486, @simonpj asks whether these techniques can disrupt confluence.
They can. (EDIT: Furthermore, more hammering in this direction discovered nonconfluence even *without* functional dependencies. See https://gitlab.haskell.org/ghc/ghc//issues/18851#note_318471.)
Here is the example:
```hs
{# LANGUAGE FunctionalDependencies, FlexibleInstances, UndecidableInstances,
ScopedTypeVariables, TypeFamilies, TypeApplications,
FlexibleContexts, AllowAmbiguousTypes #}
module Bug where
class C a b  a > b
instance C Int b => C Int b
class IsInt int
instance int ~ Int => IsInt int
data A
instance Show A where
show _ = "A"
data B
instance Show B where
show _ = "B"
f :: forall a b c int. (Show a, Show b, Show c, C int a, C int b, C int c, IsInt int) => String
f = show (undefined :: c)
g = f @A @B
```
`g` evaluates to `"B"`. If I switch the order of the `C int a` and `C int b` constraints in the type of `f`, `g` will evaluate to `"A"`. Urgh.
(Sidenote: this file needs `AllowAmbiguousTypes`, but there are no ambiguous types here. That bug is reported as #18850.)
What's going on? When calling `f` from `g`, GHC needs to figure out how to instantiate the type variables `a`, `b`, `c`, and `int`, and GHC must find dictionaries to supply for all the class constraints. First, GHC creates unification variables `a0`, `b0`, `c0`, and `int0`. The type applications tell us `a0 := A` and `b0 := B`. Good. Then we have these constraints:
```
[W] w1 : Show A
[W] w2 : Show B
[W] w3 : Show c0
[W] w4 : C int0 A
[W] w5 : C int0 B
[W] w6 : C int0 c0
[W] w7 : IsInt int0
```
GHC processes these in the order given. `w1` and `w2` are easily despatched. `w3` doesn't make any progress at all. Neither does `w4` or `w5`. So we're then in this state:
```
worklist: [W] w6 : C int0 c0
[W] w7 : IsInt int0
inerts: [W] w3 : Show c0
[W] w4 : C int0 A
[W] w5 : C int0 B
```
We then look at `w6`. It doesn't make progress. But then GHC looks at the inerts, and sees that `w4` and `w5` have the same first argument to `C` (`int0`) as the work item `w6`. Because of the functional dependency on `C`, this means that `c0` must match the second argument to `C` in the inert. The problem is that there are *two* such inerts! GHC chooses the last one, arbitrarily. Thus, we get `c0 := B` and carry on. If the constraints were processed in a different order, we'd end up with `c0 := A`. This is classic nonconfluence.
Why have `IsInt` here? It's to slow down GHC. If we just wrote an explicit `Int` in the type signature for `f`, then GHC would eagerly solve `w4' : C Int A` and `w5' : C Int B`. When processing `w6' : C Int c0`, GHC wouldn't have any inerts to look at. Instead, it would look at the instance for `C`, which is unhelpful in this case. Indeed, moving the `IsInt int` constraint earlier (before the `C` constraints) in `f`'s type signature causes GHC to error, as it doesn't know how to instantiate `c0`, having lost the hints from the inerts. (More nonconfluence!)
What to do? I think the next step is to compare this to the [constrainthandling rules paper](https://www.researchgate.net/profile/Martin_Sulzmann/publication/213885702_Understanding_Functional_Dependencies_via_Constraint_Handling_Rules/links/09e41511297969891f000000.pdf), which proves confluence, and see whether that paper has a mistake, or where GHC violates an assumption in that paper. (Probably the latter: my instance for `C` is very naughty.)https://gitlab.haskell.org/ghc/ghc//issues/18873Quantified equality constraints are not used for rewriting20201210T20:30:27ZRichard Eisenbergrae@richarde.devQuantified equality constraints are not used for rewritingIf I say
```hs
type family F a b where
F [_] b = b
f :: forall a b. (a ~ [b]) => F a b > b
f x = x
```
GHC smiles upon me: the equality constraint rewrites `a` to `[b]`, and then `F [b] b` can reduce to `b`, and all is well.
But if I say
```hs
type family F a b where
F [_] b = b
class Truth
instance Truth
f :: forall a b. (Truth => a ~ [b]) => F a b > b
f x = x
```
I get an error, saying `F a b` does not match `b`. This is because the equality, hidden behind `Truth`, is not used for rewriting, and thus GHC cannot figure out that `F a b` can reduce.
I don't see an easy solution here.
This isn't just me grousing: a problem on !4149 could be worked around if GHC used such equalities for rewriting. And so if we can solve this problem, we can solve the other one. My expectation is that we won't solve this one, though.If I say
```hs
type family F a b where
F [_] b = b
f :: forall a b. (a ~ [b]) => F a b > b
f x = x
```
GHC smiles upon me: the equality constraint rewrites `a` to `[b]`, and then `F [b] b` can reduce to `b`, and all is well.
But if I say
```hs
type family F a b where
F [_] b = b
class Truth
instance Truth
f :: forall a b. (Truth => a ~ [b]) => F a b > b
f x = x
```
I get an error, saying `F a b` does not match `b`. This is because the equality, hidden behind `Truth`, is not used for rewriting, and thus GHC cannot figure out that `F a b` can reduce.
I don't see an easy solution here.
This isn't just me grousing: a problem on !4149 could be worked around if GHC used such equalities for rewriting. And so if we can solve this problem, we can solve the other one. My expectation is that we won't solve this one, though.https://gitlab.haskell.org/ghc/ghc//issues/19010Partial type signature algorithm fails to infer constraints in the presence o...20201220T03:26:43ZsheafPartial type signature algorithm fails to infer constraints in the presence of GADTsI've been running into a few issues with partial type signatures as of late.
In my [graphics shader library](https://gitlab.com/sheaf/fir), users write programs using an indexed monad which keeps track of various pieces of information as they write the program, which are used to perform validation using type families. It would be impossible for the user to manually write the types of the indexed monad (they can become very large), so partial type signatures are a crucial tool in this situation.
However, I'm running into some situations in which GHC fails to infer a constraint, even though it is happy to report error messages that say exactly which constraints are missing.
After a fair bit of effort, I've finally managed to come up with a small reproducer:
```haskell
{# LANGUAGE DataKinds #}
{# LANGUAGE GADTs #}
{# LANGUAGE PartialTypeSignatures #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE ScopedTypeVariables #}
module Bug where
data SBool ( bool :: Bool ) where
STrue :: SBool True
SFalse :: SBool False
class C a where
methC :: a > Float
class D a where
methD :: a > Float
foo :: forall bool a. _ => SBool bool > a > Float
foo sBool a = meth a
where
meth :: _ => a > Float
meth = case sBool of
STrue > methC
SFalse > methD
```
produces the following error:
```
[1 of 1] Compiling Bug ( bug.hs, bug.o )
bug.hs:23:17: error:
* Could not deduce (C a) arising from a use of `methC'
from the context: bool ~ 'True
bound by a pattern with constructor: STrue :: SBool 'True,
in a case alternative
at bug.hs:23:711
Possible fix:
add (C a) to the context of
the inferred type of foo :: SBool bool > a > Float
* In the expression: methC
In a case alternative: STrue > methC
In the expression:
case sBool of
STrue > methC
SFalse > methD

23  STrue > methC
 ^^^^^
bug.hs:24:17: error:
* Could not deduce (D a) arising from a use of `methD'
from the context: bool ~ 'False
bound by a pattern with constructor: SFalse :: SBool 'False,
in a case alternative
at bug.hs:24:712
Possible fix:
add (D a) to the context of
the inferred type of foo :: SBool bool > a > Float
* In the expression: methD
In a case alternative: SFalse > methD
In the expression:
case sBool of
STrue > methC
SFalse > methD

24  SFalse > methD
 ^^^^^
```
If one follows the error messages that GHC provides, by adding the constraint `( C a, D a )` to `meth`, then the program compiles. So it's curious that GHC is able to pinpoint the missing constraints, but not actually put them in the hole.
I also notice that this issue remains if one uses `methC` in both branches. If one changes `SBool` to `Bool` then of course it works fine.
I assume that this happens because the partial type signature algorithm is conservative in the presence of GADTs: one could potentially learn information upon matching a GADT that would help solve the constraints, and one would not want that evidence to float out in any way. However, in this case, I think we can agree that the evidence provided by the GADT match doesn't interact in any way with the constraints on the RHS (as nothing involves `bool`), i.e. it's as if we had just matched on a `Bool`.
<hr>
Versions of GHC tried: 8.8, 8.10, 9.0 (all with the same result).I've been running into a few issues with partial type signatures as of late.
In my [graphics shader library](https://gitlab.com/sheaf/fir), users write programs using an indexed monad which keeps track of various pieces of information as they write the program, which are used to perform validation using type families. It would be impossible for the user to manually write the types of the indexed monad (they can become very large), so partial type signatures are a crucial tool in this situation.
However, I'm running into some situations in which GHC fails to infer a constraint, even though it is happy to report error messages that say exactly which constraints are missing.
After a fair bit of effort, I've finally managed to come up with a small reproducer:
```haskell
{# LANGUAGE DataKinds #}
{# LANGUAGE GADTs #}
{# LANGUAGE PartialTypeSignatures #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE ScopedTypeVariables #}
module Bug where
data SBool ( bool :: Bool ) where
STrue :: SBool True
SFalse :: SBool False
class C a where
methC :: a > Float
class D a where
methD :: a > Float
foo :: forall bool a. _ => SBool bool > a > Float
foo sBool a = meth a
where
meth :: _ => a > Float
meth = case sBool of
STrue > methC
SFalse > methD
```
produces the following error:
```
[1 of 1] Compiling Bug ( bug.hs, bug.o )
bug.hs:23:17: error:
* Could not deduce (C a) arising from a use of `methC'
from the context: bool ~ 'True
bound by a pattern with constructor: STrue :: SBool 'True,
in a case alternative
at bug.hs:23:711
Possible fix:
add (C a) to the context of
the inferred type of foo :: SBool bool > a > Float
* In the expression: methC
In a case alternative: STrue > methC
In the expression:
case sBool of
STrue > methC
SFalse > methD

23  STrue > methC
 ^^^^^
bug.hs:24:17: error:
* Could not deduce (D a) arising from a use of `methD'
from the context: bool ~ 'False
bound by a pattern with constructor: SFalse :: SBool 'False,
in a case alternative
at bug.hs:24:712
Possible fix:
add (D a) to the context of
the inferred type of foo :: SBool bool > a > Float
* In the expression: methD
In a case alternative: SFalse > methD
In the expression:
case sBool of
STrue > methC
SFalse > methD

24  SFalse > methD
 ^^^^^
```
If one follows the error messages that GHC provides, by adding the constraint `( C a, D a )` to `meth`, then the program compiles. So it's curious that GHC is able to pinpoint the missing constraints, but not actually put them in the hole.
I also notice that this issue remains if one uses `methC` in both branches. If one changes `SBool` to `Bool` then of course it works fine.
I assume that this happens because the partial type signature algorithm is conservative in the presence of GADTs: one could potentially learn information upon matching a GADT that would help solve the constraints, and one would not want that evidence to float out in any way. However, in this case, I think we can agree that the evidence provided by the GADT match doesn't interact in any way with the constraints on the RHS (as nothing involves `bool`), i.e. it's as if we had just matched on a `Bool`.
<hr>
Versions of GHC tried: 8.8, 8.10, 9.0 (all with the same result).https://gitlab.haskell.org/ghc/ghc//issues/19013Type wildcard infers differently than no type signature20201210T00:22:10ZdminuosoType wildcard infers differently than no type signature```haskell
{# LANGUAGE FlexibleContexts #}
{# LANGUAGE PartialTypeSignatures #}
module Main where
import Optics
main :: IO ()
main = putStrLn "Hello, Haskell!"
g :: Lens' String Char
g = undefined
f :: _
f o = "foo" & (g%o) .~ 10
```
Full source code of the test case at: https://gitlab.haskell.org/dminuoso/ghcwildcardbug/
The above code fails to type check with:
Without the wildcard type annotation on `f` it compiles and infers the following type for `f`:
```
*Main> :t f
f :: (Is (Join A_Lens l) A_Setter, Is l (Join A_Lens l),
Is A_Lens (Join A_Lens l), Num b) =>
Optic l js Char Char a b > String
*Main>
```
Leaving the wildcard in, the type checker bails out.
```
[nixshell:~/git/ghcwildcardbug]$ cabal build
Build profile: w ghc8.8.4 O1
In order, the following will be built (use v for more details):
 ghcwildcardbug0.1.0.0 (exe:ghcwildcardbug) (file Main.hs changed)
Preprocessing executable 'ghcwildcardbug' for ghcwildcardbug0.1.0.0..
Building executable 'ghcwildcardbug' for ghcwildcardbug0.1.0.0..
[1 of 1] Compiling Main ( Main.hs, /home/dminuoso/git/ghcwildcardbug/distnewstyle/build/x86_64linux/ghc8.8.4/ghcwildcardbug0.1.0.0/x/ghcwildcardbug/build/ghcwildcardbug/ghcwildcardbugtmp/Main.o )
Main.hs:15:15: error:
• Overlapping instances for Is (Join A_Lens l0) A_Setter
arising from a use of ‘.~’
Matching instances:
instance [overlappable] (TypeError ...) => Is k l
 Defined in ‘opticscore0.3.0.1:Optics.Internal.Optic.Subtyping’
instance Is k k
 Defined in ‘opticscore0.3.0.1:Optics.Internal.Optic.Subtyping’
instance Is A_Lens A_Setter
 Defined in ‘opticscore0.3.0.1:Optics.Internal.Optic.Subtyping’
...plus four others
(use fprintpotentialinstances to see them all)
(The choice depends on the instantiation of ‘l0’
To pick the first instance above, use IncoherentInstances
when compiling the other instance declarations)
• In the second argument of ‘(&)’, namely ‘(g % o) .~ 10’
In the expression: "foo" & (g % o) .~ 10
In an equation for ‘f’: f o = "foo" & (g % o) .~ 10

15  f o = "foo" & (g%o) .~ 10
 ^^^^^^^^^^^
Main.hs:15:16: error:
• Overlapping instances for Is l0 (Join A_Lens l0)
arising from a use of ‘%’
Matching instances:
instance [overlappable] (TypeError ...) => Is k l
 Defined in ‘opticscore0.3.0.1:Optics.Internal.Optic.Subtyping’
instance Is k k
 Defined in ‘opticscore0.3.0.1:Optics.Internal.Optic.Subtyping’
instance Is A_Getter A_Fold
 Defined in ‘opticscore0.3.0.1:Optics.Internal.Optic.Subtyping’
...plus 35 others
(use fprintpotentialinstances to see them all)
(The choice depends on the instantiation of ‘l0’
To pick the first instance above, use IncoherentInstances
when compiling the other instance declarations)
• In the first argument of ‘(.~)’, namely ‘(g % o)’
In the second argument of ‘(&)’, namely ‘(g % o) .~ 10’
In the expression: "foo" & (g % o) .~ 10

15  f o = "foo" & (g%o) .~ 10

```
Also tried enabling NoMonomorphismRestriction to no avail.```haskell
{# LANGUAGE FlexibleContexts #}
{# LANGUAGE PartialTypeSignatures #}
module Main where
import Optics
main :: IO ()
main = putStrLn "Hello, Haskell!"
g :: Lens' String Char
g = undefined
f :: _
f o = "foo" & (g%o) .~ 10
```
Full source code of the test case at: https://gitlab.haskell.org/dminuoso/ghcwildcardbug/
The above code fails to type check with:
Without the wildcard type annotation on `f` it compiles and infers the following type for `f`:
```
*Main> :t f
f :: (Is (Join A_Lens l) A_Setter, Is l (Join A_Lens l),
Is A_Lens (Join A_Lens l), Num b) =>
Optic l js Char Char a b > String
*Main>
```
Leaving the wildcard in, the type checker bails out.
```
[nixshell:~/git/ghcwildcardbug]$ cabal build
Build profile: w ghc8.8.4 O1
In order, the following will be built (use v for more details):
 ghcwildcardbug0.1.0.0 (exe:ghcwildcardbug) (file Main.hs changed)
Preprocessing executable 'ghcwildcardbug' for ghcwildcardbug0.1.0.0..
Building executable 'ghcwildcardbug' for ghcwildcardbug0.1.0.0..
[1 of 1] Compiling Main ( Main.hs, /home/dminuoso/git/ghcwildcardbug/distnewstyle/build/x86_64linux/ghc8.8.4/ghcwildcardbug0.1.0.0/x/ghcwildcardbug/build/ghcwildcardbug/ghcwildcardbugtmp/Main.o )
Main.hs:15:15: error:
• Overlapping instances for Is (Join A_Lens l0) A_Setter
arising from a use of ‘.~’
Matching instances:
instance [overlappable] (TypeError ...) => Is k l
 Defined in ‘opticscore0.3.0.1:Optics.Internal.Optic.Subtyping’
instance Is k k
 Defined in ‘opticscore0.3.0.1:Optics.Internal.Optic.Subtyping’
instance Is A_Lens A_Setter
 Defined in ‘opticscore0.3.0.1:Optics.Internal.Optic.Subtyping’
...plus four others
(use fprintpotentialinstances to see them all)
(The choice depends on the instantiation of ‘l0’
To pick the first instance above, use IncoherentInstances
when compiling the other instance declarations)
• In the second argument of ‘(&)’, namely ‘(g % o) .~ 10’
In the expression: "foo" & (g % o) .~ 10
In an equation for ‘f’: f o = "foo" & (g % o) .~ 10

15  f o = "foo" & (g%o) .~ 10
 ^^^^^^^^^^^
Main.hs:15:16: error:
• Overlapping instances for Is l0 (Join A_Lens l0)
arising from a use of ‘%’
Matching instances:
instance [overlappable] (TypeError ...) => Is k l
 Defined in ‘opticscore0.3.0.1:Optics.Internal.Optic.Subtyping’
instance Is k k
 Defined in ‘opticscore0.3.0.1:Optics.Internal.Optic.Subtyping’
instance Is A_Getter A_Fold
 Defined in ‘opticscore0.3.0.1:Optics.Internal.Optic.Subtyping’
...plus 35 others
(use fprintpotentialinstances to see them all)
(The choice depends on the instantiation of ‘l0’
To pick the first instance above, use IncoherentInstances
when compiling the other instance declarations)
• In the first argument of ‘(.~)’, namely ‘(g % o)’
In the second argument of ‘(&)’, namely ‘(g % o) .~ 10’
In the expression: "foo" & (g % o) .~ 10

15  f o = "foo" & (g%o) .~ 10

```
Also tried enabling NoMonomorphismRestriction to no avail.https://gitlab.haskell.org/ghc/ghc//issues/19051Allow named wildcards in constraints20201223T15:23:55ZsheafAllow named wildcards in constraints```haskell
{# LANGUAGE ConstraintKinds #}
{# LANGUAGE NamedWildCards #}
{# LANGUAGE PartialTypeSignatures #}
module Test where
class C a where
meth :: a
unnamed :: _ => a
unnamed = meth
named :: _c => a
named = meth
```
The `unnamed` version causes no problems, however `named` causes the following error:
```
* Could not deduce: _0
from the context: _
bound by the inferred type for `named':
forall a (_ :: Constraint). _ => a
at Test.hs:14:112
* In the ambiguity check for the inferred type for `named'
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
When checking the inferred type
named :: forall a (_ :: Constraint). _ => a

14  named = meth
 ^^^^^^^^^^^^
```
That is, in this example, `_c` is **not** a named wildcard, but is instead universally quantified. So GHC unsurprisingly throws the same error as if we had written
```haskell
universal :: c => a
universal = meth
```
I would have expected that the named wildcard `_c` behave just like the wildcard `_`, except that it would give me the ability to refer to the inferred constraint at the typelevel inside the body of `named`.
(I came across this while thinking about #19010.)```haskell
{# LANGUAGE ConstraintKinds #}
{# LANGUAGE NamedWildCards #}
{# LANGUAGE PartialTypeSignatures #}
module Test where
class C a where
meth :: a
unnamed :: _ => a
unnamed = meth
named :: _c => a
named = meth
```
The `unnamed` version causes no problems, however `named` causes the following error:
```
* Could not deduce: _0
from the context: _
bound by the inferred type for `named':
forall a (_ :: Constraint). _ => a
at Test.hs:14:112
* In the ambiguity check for the inferred type for `named'
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
When checking the inferred type
named :: forall a (_ :: Constraint). _ => a

14  named = meth
 ^^^^^^^^^^^^
```
That is, in this example, `_c` is **not** a named wildcard, but is instead universally quantified. So GHC unsurprisingly throws the same error as if we had written
```haskell
universal :: c => a
universal = meth
```
I would have expected that the named wildcard `_c` behave just like the wildcard `_`, except that it would give me the ability to refer to the inferred constraint at the typelevel inside the body of `named`.
(I came across this while thinking about #19010.)https://gitlab.haskell.org/ghc/ghc//issues/19060Make the canonicaliser do unification20201214T15:23:24ZSimon Peyton JonesMake the canonicaliser do unificationLook at `canEqTyVarFunEqCan`
* This function calls `unifyTest`, and `checkTyVarEq`, both of which are fairly elaborate tests.
* Then we go to `canEqCanLHSFinish`, which calls `canEqOK` which calls `checkTypeEq`, repeating that `checkTyVarEq`
* All this just gets the orientation right. Then we forget all that, and later, in `tryToSolveByUnification` we call `unifyTest` again. What a mess.
One thing that discouraged me was the miasma of `rewriteEqEvidence` and `rewriteCastedEquality` and doswap stuff. I just can't get my head round it. In some of my traces (eg EqCanOccursCheck) we seem to swap and swap back. Bizarre.
@rae and I agree that the canonicaliser should just do unification on the spot. This ticket is to track that point.Look at `canEqTyVarFunEqCan`
* This function calls `unifyTest`, and `checkTyVarEq`, both of which are fairly elaborate tests.
* Then we go to `canEqCanLHSFinish`, which calls `canEqOK` which calls `checkTypeEq`, repeating that `checkTyVarEq`
* All this just gets the orientation right. Then we forget all that, and later, in `tryToSolveByUnification` we call `unifyTest` again. What a mess.
One thing that discouraged me was the miasma of `rewriteEqEvidence` and `rewriteCastedEquality` and doswap stuff. I just can't get my head round it. In some of my traces (eg EqCanOccursCheck) we seem to swap and swap back. Bizarre.
@rae and I agree that the canonicaliser should just do unification on the spot. This ticket is to track that point.https://gitlab.haskell.org/ghc/ghc//issues/19131Does the subtype check in Note [Impedance matching] ever fail?20210217T13:00:27ZRichard Eisenbergrae@richarde.devDoes the subtype check in Note [Impedance matching] ever fail?`GHC.Tc.Gen.Bind` tells us
```
Note [Impedance matching]
~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f 0 x = x
f n x = g [] (not x)
g [] y = f 10 y
g _ y = f 9 y
After typechecking we'll get
f_mono_ty :: a > Bool > Bool
g_mono_ty :: [b] > Bool > Bool
with constraints
(Eq a, Num a)
Note that f is polymorphic in 'a' and g in 'b'; and these are not linked.
The types we really want for f and g are
f :: forall a. (Eq a, Num a) => a > Bool > Bool
g :: forall b. [b] > Bool > Bool
We can get these by "impedance matching":
tuple :: forall a b. (Eq a, Num a) => (a > Bool > Bool, [b] > Bool > Bool)
tuple a b d1 d1 = let ...bind f_mono, g_mono in (f_mono, g_mono)
f a d1 d2 = case tuple a Any d1 d2 of (f, g) > f
g b = case tuple Integer b dEqInteger dNumInteger of (f,g) > g
Suppose the shared quantified tyvars are qtvs and constraints theta.
Then we want to check that
forall qtvs. theta => f_mono_ty is more polymorphic than f's polytype
and the proof is the impedance matcher.
Notice that the impedance matcher may do defaulting. See #7173.
It also cleverly does an ambiguity check; for example, rejecting
f :: F a > F a
where F is a noninjective type function.
```
This describes a subtype check. That subtype check is performed with the context returned from this function:
```hs
mk_impedance_match_msg :: MonoBindInfo
> TcType > TcType
> TidyEnv > TcM (TidyEnv, SDoc)
 This is a rare but rather awkward error messages
mk_impedance_match_msg (MBI { mbi_poly_name = name, mbi_sig = mb_sig })
inf_ty sig_ty tidy_env
= do { (tidy_env1, inf_ty) < zonkTidyTcType tidy_env inf_ty
; (tidy_env2, sig_ty) < zonkTidyTcType tidy_env1 sig_ty
; let msg = vcat [ text "When checking that the inferred type"
, nest 2 $ ppr name <+> dcolon <+> ppr inf_ty
, text "is as general as its" <+> what <+> text "signature"
, nest 2 $ ppr name <+> dcolon <+> ppr sig_ty ]
; return (tidy_env2, msg) }
where
what = case mb_sig of
Nothing > text "inferred"
Just sig  isPartialSig sig > text "(partial)"
 otherwise > empty
```
A search in the testsuite shows no occurrence of "When checking that the inferred type".
So: Does this subtype check ever fail? If so, we should have a test case in the testsuite for this message. If not, we should explain why failure is impossible and then remove the above function.`GHC.Tc.Gen.Bind` tells us
```
Note [Impedance matching]
~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f 0 x = x
f n x = g [] (not x)
g [] y = f 10 y
g _ y = f 9 y
After typechecking we'll get
f_mono_ty :: a > Bool > Bool
g_mono_ty :: [b] > Bool > Bool
with constraints
(Eq a, Num a)
Note that f is polymorphic in 'a' and g in 'b'; and these are not linked.
The types we really want for f and g are
f :: forall a. (Eq a, Num a) => a > Bool > Bool
g :: forall b. [b] > Bool > Bool
We can get these by "impedance matching":
tuple :: forall a b. (Eq a, Num a) => (a > Bool > Bool, [b] > Bool > Bool)
tuple a b d1 d1 = let ...bind f_mono, g_mono in (f_mono, g_mono)
f a d1 d2 = case tuple a Any d1 d2 of (f, g) > f
g b = case tuple Integer b dEqInteger dNumInteger of (f,g) > g
Suppose the shared quantified tyvars are qtvs and constraints theta.
Then we want to check that
forall qtvs. theta => f_mono_ty is more polymorphic than f's polytype
and the proof is the impedance matcher.
Notice that the impedance matcher may do defaulting. See #7173.
It also cleverly does an ambiguity check; for example, rejecting
f :: F a > F a
where F is a noninjective type function.
```
This describes a subtype check. That subtype check is performed with the context returned from this function:
```hs
mk_impedance_match_msg :: MonoBindInfo
> TcType > TcType
> TidyEnv > TcM (TidyEnv, SDoc)
 This is a rare but rather awkward error messages
mk_impedance_match_msg (MBI { mbi_poly_name = name, mbi_sig = mb_sig })
inf_ty sig_ty tidy_env
= do { (tidy_env1, inf_ty) < zonkTidyTcType tidy_env inf_ty
; (tidy_env2, sig_ty) < zonkTidyTcType tidy_env1 sig_ty
; let msg = vcat [ text "When checking that the inferred type"
, nest 2 $ ppr name <+> dcolon <+> ppr inf_ty
, text "is as general as its" <+> what <+> text "signature"
, nest 2 $ ppr name <+> dcolon <+> ppr sig_ty ]
; return (tidy_env2, msg) }
where
what = case mb_sig of
Nothing > text "inferred"
Just sig  isPartialSig sig > text "(partial)"
 otherwise > empty
```
A search in the testsuite shows no occurrence of "When checking that the inferred type".
So: Does this subtype check ever fail? If so, we should have a test case in the testsuite for this message. If not, we should explain why failure is impossible and then remove the above function.https://gitlab.haskell.org/ghc/ghc//issues/19137Incorrect documentation around EqualCtList20201230T19:59:58ZRichard Eisenbergrae@richarde.devIncorrect documentation around EqualCtListThe solver maintains a structure `EqualCtList`, with this Note:
```
Note [EqualCtList invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* All are equalities
* All these equalities have the same LHS
* The list is never empty
* No element of the list can rewrite any other
* Derived before Wanted
From the fourth invariant it follows that the list is
 A single [G], or
 Zero or one [D] or [WD], followed by any number of [W]
The Wanteds can't rewrite anything which is why we put them last
```
Yet this isn't quite accurate. If we have a `[G] a ~R Bool` and a `[D] a ~ Int`, neither can rewrite the other. Both can live in the `EqualCtList` quite peacefully. Thus, the "it follows that" is wrong. Worse, the rewriter contains the code
```hs
; case lookupDVarEnv ieqs tv of
Just (EqualCtList (ct : _))  If the first doesn't work,
 the subsequent ones won't either
 CEqCan { cc_ev = ctev, cc_lhs = TyVarLHS tv
, cc_rhs = rhs_ty, cc_eq_rel = ct_eq_rel } < ct
```
but the comment there isn't true: the first might not work, but maybe a later one will.
I tried quite hard to come up with some misbehavior that this misunderstanding caused, but it's quite hard. An example with a Given that contains a touchable metavariable wouldn't be convincing (#18929), and all other examples seem to lead to program rejection. And because the prioritization of some errors over others, it's hard to see the bad error.
Yet I still think there is a problem here, and that we should search through the list looking for a valid inert.The solver maintains a structure `EqualCtList`, with this Note:
```
Note [EqualCtList invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* All are equalities
* All these equalities have the same LHS
* The list is never empty
* No element of the list can rewrite any other
* Derived before Wanted
From the fourth invariant it follows that the list is
 A single [G], or
 Zero or one [D] or [WD], followed by any number of [W]
The Wanteds can't rewrite anything which is why we put them last
```
Yet this isn't quite accurate. If we have a `[G] a ~R Bool` and a `[D] a ~ Int`, neither can rewrite the other. Both can live in the `EqualCtList` quite peacefully. Thus, the "it follows that" is wrong. Worse, the rewriter contains the code
```hs
; case lookupDVarEnv ieqs tv of
Just (EqualCtList (ct : _))  If the first doesn't work,
 the subsequent ones won't either
 CEqCan { cc_ev = ctev, cc_lhs = TyVarLHS tv
, cc_rhs = rhs_ty, cc_eq_rel = ct_eq_rel } < ct
```
but the comment there isn't true: the first might not work, but maybe a later one will.
I tried quite hard to come up with some misbehavior that this misunderstanding caused, but it's quite hard. An example with a Given that contains a touchable metavariable wouldn't be convincing (#18929), and all other examples seem to lead to program rejection. And because the prioritization of some errors over others, it's hard to see the bad error.
Yet I still think there is a problem here, and that we should search through the list looking for a valid inert.https://gitlab.haskell.org/ghc/ghc//issues/19272EGraphs for representation of normalised refinement types in the patternmat...20210618T07:16:27ZSebastian GrafEGraphs for representation of normalised refinement types in the patternmatch checkerI realised today that the quite complicated data structure+invariants (`Nabla`'s [`TmState`](https://gitlab.haskell.org/ghc/ghc//blob/0249974e7622e35927060da21f9231cb1e6357b9/compiler/GHC/HsToCore/Pmc/Solver/Types.hs#L125142)) we use while patternmatch coverage checking fits "egraphs" quite well.
I realised so while reading the POPL 2021 paper [*`egg`: Fast and Extensible Equality Saturation*](https://arxiv.org/abs/2004.03082). The similarity is striking. I think the inhabitation test could probably be expressed as an egraph analysis.
To be a bit more concrete, an egraph is basically a unionfind data structure on terms. If we start with the disjoint equality classes `{Just x}, {Just y}, {x}, {y}` and later find out that `x ~ y`, we'd `merge` the equality classes `{x}` and `{y}`. The egraph data structure then restores congruence, putting `Just x` and `Just y` into the same equality class as well: `{Just x, Just y}, {x, y}`. Note how this also puts the "CSE" pass envisioned in #17208 on firm ground. There we have
```hs
safeLast3 :: [a] > Maybe a
safeLast3 xs
 [] < reverse xs = Nothing
safeLast3 xs'
 (x:_) < reverse xs' = Just x
```
To see that the match is exhaustive, we have to see that `reverse xs ~ reverse xs'` from `xs ~ xs'`. This is exactly the kind of congruence that egraphs maintain: Replace `Just` by `reverse` in the example above. (It does so via a technique called "upward merge" that we'd have to implement in an adhoc manner to fix #17208).
The egraph representation is quite compact and trivially supports the ∆(x) lookup from the paper (it's just the `find` operation), and extends it to expressions, ∆(e), via `canonicalize`.
While I think this is an important and useful observation, I'm not so keen about implementing it; it's a bit unclear to me if we can retain the same (mostly sufficient) efficiency that our checker has today, and #17208 alone is not compelling enough of a use case for me to pursue.
Maybe that data structure would be useful in other parts of GHC as well. I imagine that Type Family rewrites fit into the same framework. It was conceived for theorem provers, after all. Maybe it's also a useful representation for the Simplifier, although implementing it would be a huge change with possibly daunting repercussions. Still, a good data structure to have up one's sleeve.I realised today that the quite complicated data structure+invariants (`Nabla`'s [`TmState`](https://gitlab.haskell.org/ghc/ghc//blob/0249974e7622e35927060da21f9231cb1e6357b9/compiler/GHC/HsToCore/Pmc/Solver/Types.hs#L125142)) we use while patternmatch coverage checking fits "egraphs" quite well.
I realised so while reading the POPL 2021 paper [*`egg`: Fast and Extensible Equality Saturation*](https://arxiv.org/abs/2004.03082). The similarity is striking. I think the inhabitation test could probably be expressed as an egraph analysis.
To be a bit more concrete, an egraph is basically a unionfind data structure on terms. If we start with the disjoint equality classes `{Just x}, {Just y}, {x}, {y}` and later find out that `x ~ y`, we'd `merge` the equality classes `{x}` and `{y}`. The egraph data structure then restores congruence, putting `Just x` and `Just y` into the same equality class as well: `{Just x, Just y}, {x, y}`. Note how this also puts the "CSE" pass envisioned in #17208 on firm ground. There we have
```hs
safeLast3 :: [a] > Maybe a
safeLast3 xs
 [] < reverse xs = Nothing
safeLast3 xs'
 (x:_) < reverse xs' = Just x
```
To see that the match is exhaustive, we have to see that `reverse xs ~ reverse xs'` from `xs ~ xs'`. This is exactly the kind of congruence that egraphs maintain: Replace `Just` by `reverse` in the example above. (It does so via a technique called "upward merge" that we'd have to implement in an adhoc manner to fix #17208).
The egraph representation is quite compact and trivially supports the ∆(x) lookup from the paper (it's just the `find` operation), and extends it to expressions, ∆(e), via `canonicalize`.
While I think this is an important and useful observation, I'm not so keen about implementing it; it's a bit unclear to me if we can retain the same (mostly sufficient) efficiency that our checker has today, and #17208 alone is not compelling enough of a use case for me to pursue.
Maybe that data structure would be useful in other parts of GHC as well. I imagine that Type Family rewrites fit into the same framework. It was conceived for theorem provers, after all. Maybe it's also a useful representation for the Simplifier, although implementing it would be a huge change with possibly daunting repercussions. Still, a good data structure to have up one's sleeve.https://gitlab.haskell.org/ghc/ghc//issues/19428Deprecate `Winaccessiblecode`20210505T21:40:43ZSebastian GrafDeprecate `Winaccessiblecode`In https://gitlab.haskell.org/ghc/ghc//merge_requests/5100#note_333682, the special role of `Winaccessiblecode` came up. In particular, how it's not integrated well with the rest of how the patternmatch checker works today. For one, it's implemented somewhere in the typechecker, I think. But I also think its purpose is subsumed by `Woverlappingpatterns` (which will warn for *any* inaccessible RHS, not just those caused by contradictory type constraints) noawadays.
I propose to deprecate the flag.In https://gitlab.haskell.org/ghc/ghc//merge_requests/5100#note_333682, the special role of `Winaccessiblecode` came up. In particular, how it's not integrated well with the rest of how the patternmatch checker works today. For one, it's implemented somewhere in the typechecker, I think. But I also think its purpose is subsumed by `Woverlappingpatterns` (which will warn for *any* inaccessible RHS, not just those caused by contradictory type constraints) noawadays.
I propose to deprecate the flag.https://gitlab.haskell.org/ghc/ghc//issues/19482"No skolem info" with the infinite kind20210630T10:40:36ZRinat Striungis"No skolem info" with the infinite kind## Summary
Today I get a crash with the following message:
```src/Bug.hs:12:25: error:ghc: panic! (the 'impossible' happened)
(GHC version 9.1.20210210:
No skolem info:
[r_axQl[ssk:1]]
Call stack:
CallStack (from HasCallStack):
callStackDoc, called at compiler/GHC/Utils/Panic.hs:181:37 in ghc:GHC.Utils.Panic
pprPanic, called at compiler/GHC/Tc/Errors.hs:2847:17 in ghc:GHC.Tc.Errors
Please report this as a GHC bug: https://www.haskell.org/ghc/reportabug
```
## Steps to reproduce
Here is my minimal example to reproduce:
```{# LANGUAGE FlexibleInstances #}
{# LANGUAGE DataKinds #}
{# LANGUAGE TypeOperators #}
{# LANGUAGE TypeApplications #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE ScopedTypeVariables #}
{# LANGUAGE AllowAmbiguousTypes #}
module Bug where
instance BugClass ((s : sx) :: [r]) where
bugList = testF @r @s
class BugClass k where
bugList :: ()
testF :: forall a (b :: [a]). ()
testF = ()
```
Also, GHC8.10 works well with a proper error message.
So, it looks like a regression.
## Expected behavior
I should get a compilation error message about the infinite kind construction ( `r ~ [r]`).
## Environment
* GHC version used:
GHC HEAD: [40983d2331fe34c0af6925db7588d5ac6a19ae36](https://gitlab.haskell.org/ghc/ghc//tree/40983d2331fe34c0af6925db7588d5ac6a19ae36)## Summary
Today I get a crash with the following message:
```src/Bug.hs:12:25: error:ghc: panic! (the 'impossible' happened)
(GHC version 9.1.20210210:
No skolem info:
[r_axQl[ssk:1]]
Call stack:
CallStack (from HasCallStack):
callStackDoc, called at compiler/GHC/Utils/Panic.hs:181:37 in ghc:GHC.Utils.Panic
pprPanic, called at compiler/GHC/Tc/Errors.hs:2847:17 in ghc:GHC.Tc.Errors
Please report this as a GHC bug: https://www.haskell.org/ghc/reportabug
```
## Steps to reproduce
Here is my minimal example to reproduce:
```{# LANGUAGE FlexibleInstances #}
{# LANGUAGE DataKinds #}
{# LANGUAGE TypeOperators #}
{# LANGUAGE TypeApplications #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE ScopedTypeVariables #}
{# LANGUAGE AllowAmbiguousTypes #}
module Bug where
instance BugClass ((s : sx) :: [r]) where
bugList = testF @r @s
class BugClass k where
bugList :: ()
testF :: forall a (b :: [a]). ()
testF = ()
```
Also, GHC8.10 works well with a proper error message.
So, it looks like a regression.
## Expected behavior
I should get a compilation error message about the infinite kind construction ( `r ~ [r]`).
## Environment
* GHC version used:
GHC HEAD: [40983d2331fe34c0af6925db7588d5ac6a19ae36](https://gitlab.haskell.org/ghc/ghc//tree/40983d2331fe34c0af6925db7588d5ac6a19ae36)9.2.1https://gitlab.haskell.org/ghc/ghc//issues/19487Relax Note [Phantom type variables in kinds] to allow for phantom levity vars20210602T10:27:07ZSebastian GrafRelax Note [Phantom type variables in kinds] to allow for phantom levity varsWhile implementing the unlifted datatypes proposal (!2218), I realised that an edge case violates the kinding rules (`Note [Phantom type variables in kinds]`, in particular). Specifically
```hs
type T :: forall (l :: Levity). TYPE (BoxedRep l)
data T = MkT
```
Note that
1. `T` has a nullary data con `MkT`
2. `T` is levitypolymorphic
That means the type of `MkT`, `forall {l::Levity}. T @l`, is illkinded! We have `T @l :: TYPE (BoxedRep l)` and the `forall` is supposed to bind the `l`. But the kind rule for `forall a. TYPE rep` demands that `a` is not free in `rep`:
```
ty : TYPE rep
`a` is not free in rep
(FORALL1) 
forall a. ty : TYPE rep
```
I argue that there is no harm in allowing `TYPE (BoxedRep l)` here, because `l` does not affect the *representation* of `T`. I'm unaware of any other implications this might have.
We have to be a bit careful with evaluation semantics, but we have better means (https://gitlab.haskell.org/ghc/ghc//issues/15532#note_239845, #17521) to decide whether levity polymorphism is OK at the term level. In any instance, `MkT` is a data constructor and thus is a value under both callbyneed and callbyvalue semantics. I'm reasonably positive that allowing `MkT` to be wellkinded is OK. You can't do anything with it at the term level unless you apply it to a `Levity` anyway.While implementing the unlifted datatypes proposal (!2218), I realised that an edge case violates the kinding rules (`Note [Phantom type variables in kinds]`, in particular). Specifically
```hs
type T :: forall (l :: Levity). TYPE (BoxedRep l)
data T = MkT
```
Note that
1. `T` has a nullary data con `MkT`
2. `T` is levitypolymorphic
That means the type of `MkT`, `forall {l::Levity}. T @l`, is illkinded! We have `T @l :: TYPE (BoxedRep l)` and the `forall` is supposed to bind the `l`. But the kind rule for `forall a. TYPE rep` demands that `a` is not free in `rep`:
```
ty : TYPE rep
`a` is not free in rep
(FORALL1) 
forall a. ty : TYPE rep
```
I argue that there is no harm in allowing `TYPE (BoxedRep l)` here, because `l` does not affect the *representation* of `T`. I'm unaware of any other implications this might have.
We have to be a bit careful with evaluation semantics, but we have better means (https://gitlab.haskell.org/ghc/ghc//issues/15532#note_239845, #17521) to decide whether levity polymorphism is OK at the term level. In any instance, `MkT` is a data constructor and thus is a value under both callbyneed and callbyvalue semantics. I'm reasonably positive that allowing `MkT` to be wellkinded is OK. You can't do anything with it at the term level unless you apply it to a `Levity` anyway.https://gitlab.haskell.org/ghc/ghc//issues/19503Dead suggestion for XUnliftedNewtypes in checkNewDataCon20210308T17:40:04ZSebastian GrafDead suggestion for XUnliftedNewtypes in checkNewDataConNote [Implementation of UnliftedNewtypes], point <Error Messages> says:
```
<Error Messages>: It's tempting to think that the expected kind for a newtype
constructor argument when XUnliftedNewtypes is *not* enabled should just be Type.
But this leads to difficulty in suggesting to enable UnliftedNewtypes. Here is
an example:
newtype A = MkA Int#
If we expect the argument to MkA to have kind Type, then we get a kindmismatch
error. The problem is that there is no way to connect this mismatch error to
XUnliftedNewtypes, and suggest enabling the extension. So, instead, we allow
the A to typecheck, but then find the problem when doing validity checking (and
where we get make a suitable error message).
```
I think that Note refers to the code in `GHC.Tc.TyCl.checkNewDataCon` (which is transitively called from `checkValidTyCon`). There we have
```hs
; unlifted_newtypes < xoptM LangExt.UnliftedNewtypes
; let allowedArgType =
unlifted_newtypes  isLiftedType_maybe (scaledThing arg_ty1) == Just True
; checkTc allowedArgType $ vcat
[ text "A newtype cannot have an unlifted argument type"
, text "Perhaps you intended to use UnliftedNewtypes"
]
```
But that error emssage doesn't occur anywhere in the testsuite. If you try the example `A` from the Note, you instead get
```
test.hs:20:1: error:
• Newtype has non* return kind ‘TYPE 'IntRep’
Perhaps you intended to use UnliftedNewtypes
• In the newtype declaration for ‘A’

20  newtype A = MkA Int#
 ^^^^^^^^^^^^^^^^^^^^
```
(Side note: It's a bit surprising that the emission of that error suppresses any following errors, for example of a following decl `newtype B = MkB Int#`. Perhaps this has to do with the next paragraph.)
That message (which I actually prefer) is emitted by `GHC.Tc.Gen.HsType.checkDataKindSig`.
It seems we can just get rid of the code in `checkNewDataCon`. Either way, we should update Note [Implementation of UnliftedNewtypes]. Maybe Split if off into its own SubNote? That Note is awfully long and has many many sub items.Note [Implementation of UnliftedNewtypes], point <Error Messages> says:
```
<Error Messages>: It's tempting to think that the expected kind for a newtype
constructor argument when XUnliftedNewtypes is *not* enabled should just be Type.
But this leads to difficulty in suggesting to enable UnliftedNewtypes. Here is
an example:
newtype A = MkA Int#
If we expect the argument to MkA to have kind Type, then we get a kindmismatch
error. The problem is that there is no way to connect this mismatch error to
XUnliftedNewtypes, and suggest enabling the extension. So, instead, we allow
the A to typecheck, but then find the problem when doing validity checking (and
where we get make a suitable error message).
```
I think that Note refers to the code in `GHC.Tc.TyCl.checkNewDataCon` (which is transitively called from `checkValidTyCon`). There we have
```hs
; unlifted_newtypes < xoptM LangExt.UnliftedNewtypes
; let allowedArgType =
unlifted_newtypes  isLiftedType_maybe (scaledThing arg_ty1) == Just True
; checkTc allowedArgType $ vcat
[ text "A newtype cannot have an unlifted argument type"
, text "Perhaps you intended to use UnliftedNewtypes"
]
```
But that error emssage doesn't occur anywhere in the testsuite. If you try the example `A` from the Note, you instead get
```
test.hs:20:1: error:
• Newtype has non* return kind ‘TYPE 'IntRep’
Perhaps you intended to use UnliftedNewtypes
• In the newtype declaration for ‘A’

20  newtype A = MkA Int#
 ^^^^^^^^^^^^^^^^^^^^
```
(Side note: It's a bit surprising that the emission of that error suppresses any following errors, for example of a following decl `newtype B = MkB Int#`. Perhaps this has to do with the next paragraph.)
That message (which I actually prefer) is emitted by `GHC.Tc.Gen.HsType.checkDataKindSig`.
It seems we can just get rid of the code in `checkNewDataCon`. Either way, we should update Note [Implementation of UnliftedNewtypes]. Maybe Split if off into its own SubNote? That Note is awfully long and has many many sub items.https://gitlab.haskell.org/ghc/ghc//issues/19559The GHCi debugger loses type constraints20210415T01:20:56ZRoland SennThe GHCi debugger loses type constraints## Summary
The GHCi debugger loses the type constraints of the breakpoint variables..
## Steps to reproduce
`Foo.hs` is a simplified version of testcase `break012`:
````
foo :: (Num a1, Num a2) => a2 > (a2, a1 > a1 > a1)
foo i = let incr = i + 1
add = (+)
in (incr,add)
````
Observe the following GHCi session:
````
$ ghci Foo.hs
GHCi, version 9.0.1: https://www.haskell.org/ghc/ :? for help
[1 of 1] Compiling Main ( Foo.hs, interpreted )
Ok, one module loaded.
ghci> :st foo 5 `seq` ()
Stopped in Main.foo, Foo.hs:4:1221
_result :: (a2, a1 > a1 > a1) = _
add :: a1 > a1 > a1 = _
incr :: a2 = _
[Foo.hs:4:1221] ghci> add 40 2
<interactive>:2:5: error:
• No instance for (Num a1) arising from the literal ‘40’
Cannot resolve unknown runtime type ‘a1’
Use :print or :force to determine these types
Relevant bindings include it :: a1 (bound at <interactive>:2:1)
These potential instances exist:
instance Num Integer  Defined in ‘GHC.Num’
instance Num Double  Defined in ‘GHC.Float’
instance Num Float  Defined in ‘GHC.Float’
...plus two others
...plus one instance involving outofscope types
(use fprintpotentialinstances to see them all)
• In the first argument of ‘add’, namely ‘40’
In the expression: add 40 2
In an equation for ‘it’: it = add 40 2
[Foo.hs:4:1221] ghci>
````
The types of all breakpoint variables lack `Num` contraints!
## Expected behavior
The types of all 3 breakpoint variables (`_result`, `add`, `incr`) should have one or two `Num` constraints. The correct types are:
````
_result :: (Num a1, Num a2) => a2 > (a2, a1 > a1 > a1) = _ ( or _result :: Integer = _ )
add :: Num a1 => a1 > a1 > a1 = _
incr :: Num a1 => a2 = _
````
The result of `add 40 2` should be `42` and not an error message.
## Environment
* GHC versions used: 7.10.3, 8.10.2, 9.0.1, HEAD
(in 7.10.3 only the `_result` breakpoint variable is shown)
* Operating System: Linux Debian 10
* System Architecture: x86_64## Summary
The GHCi debugger loses the type constraints of the breakpoint variables..
## Steps to reproduce
`Foo.hs` is a simplified version of testcase `break012`:
````
foo :: (Num a1, Num a2) => a2 > (a2, a1 > a1 > a1)
foo i = let incr = i + 1
add = (+)
in (incr,add)
````
Observe the following GHCi session:
````
$ ghci Foo.hs
GHCi, version 9.0.1: https://www.haskell.org/ghc/ :? for help
[1 of 1] Compiling Main ( Foo.hs, interpreted )
Ok, one module loaded.
ghci> :st foo 5 `seq` ()
Stopped in Main.foo, Foo.hs:4:1221
_result :: (a2, a1 > a1 > a1) = _
add :: a1 > a1 > a1 = _
incr :: a2 = _
[Foo.hs:4:1221] ghci> add 40 2
<interactive>:2:5: error:
• No instance for (Num a1) arising from the literal ‘40’
Cannot resolve unknown runtime type ‘a1’
Use :print or :force to determine these types
Relevant bindings include it :: a1 (bound at <interactive>:2:1)
These potential instances exist:
instance Num Integer  Defined in ‘GHC.Num’
instance Num Double  Defined in ‘GHC.Float’
instance Num Float  Defined in ‘GHC.Float’
...plus two others
...plus one instance involving outofscope types
(use fprintpotentialinstances to see them all)
• In the first argument of ‘add’, namely ‘40’
In the expression: add 40 2
In an equation for ‘it’: it = add 40 2
[Foo.hs:4:1221] ghci>
````
The types of all breakpoint variables lack `Num` contraints!
## Expected behavior
The types of all 3 breakpoint variables (`_result`, `add`, `incr`) should have one or two `Num` constraints. The correct types are:
````
_result :: (Num a1, Num a2) => a2 > (a2, a1 > a1 > a1) = _ ( or _result :: Integer = _ )
add :: Num a1 => a1 > a1 > a1 = _
incr :: Num a1 => a2 = _
````
The result of `add 40 2` should be `42` and not an error message.
## Environment
* GHC versions used: 7.10.3, 8.10.2, 9.0.1, HEAD
(in 7.10.3 only the `_result` breakpoint variable is shown)
* Operating System: Linux Debian 10
* System Architecture: x86_64https://gitlab.haskell.org/ghc/ghc//issues/19634Implement type family reduction via termlevel functions20210628T07:38:33ZRinat StriungisImplement type family reduction via termlevel functions## Motivation
Today I see two problems:
1. Type family reduction could be painfully slow.
In a complex case (typelevel parser) rewriter took \~ 50% compilation time.
[Example](https://gist.github.com/Haskellmouse/b05db12de9e9fdc8cfa9b02f436eccc0#file1profilingwopatchtxt).
2. Writing base type families could cause one of two unwanted consequences:
1. In the case of adding them as builtin type families code base of GHC could be terribly grown.
[First char kind MR for example](https://gitlab.haskell.org/ghc/ghc//merge_requests/3598).
This MR includes many useful type families, but it was decided to make a smaller MR with only a few TFs to
avoid increasing GHC codebase for \~ 2000 lines mostly because of TFs.
2. Adding them via plugins is a painful process for developers at least because they have to track all changes in unstable GHC plugin API.
In both cases, developers have to learn many implementation details and internals of GHC.
## Proposal
I want to add a new **TYPEFUN** pragma, which works in the following way:
```type IsAlphaNum :: Char > Bool
type family IsAlphaNum c
{# TYPEFUN IsAlphaNum = Data.Char.isAlphaNum #}
```
1. This pragma says which termlevel function use for reducing type family.
2. It reduces only when inputs contain no type variables.
3. It works only when all types (both arguments and result) are promotable in any way.
The main idea is to use precompiled to bytecode termlevel functions
in process of type checking which should solve both problems from the motivation part:
accelerate type family reduction and make writing TFs much easier.## Motivation
Today I see two problems:
1. Type family reduction could be painfully slow.
In a complex case (typelevel parser) rewriter took \~ 50% compilation time.
[Example](https://gist.github.com/Haskellmouse/b05db12de9e9fdc8cfa9b02f436eccc0#file1profilingwopatchtxt).
2. Writing base type families could cause one of two unwanted consequences:
1. In the case of adding them as builtin type families code base of GHC could be terribly grown.
[First char kind MR for example](https://gitlab.haskell.org/ghc/ghc//merge_requests/3598).
This MR includes many useful type families, but it was decided to make a smaller MR with only a few TFs to
avoid increasing GHC codebase for \~ 2000 lines mostly because of TFs.
2. Adding them via plugins is a painful process for developers at least because they have to track all changes in unstable GHC plugin API.
In both cases, developers have to learn many implementation details and internals of GHC.
## Proposal
I want to add a new **TYPEFUN** pragma, which works in the following way:
```type IsAlphaNum :: Char > Bool
type family IsAlphaNum c
{# TYPEFUN IsAlphaNum = Data.Char.isAlphaNum #}
```
1. This pragma says which termlevel function use for reducing type family.
2. It reduces only when inputs contain no type variables.
3. It works only when all types (both arguments and result) are promotable in any way.
The main idea is to use precompiled to bytecode termlevel functions
in process of type checking which should solve both problems from the motivation part:
accelerate type family reduction and make writing TFs much easier.9.4.1https://gitlab.haskell.org/ghc/ghc//issues/19652GHC's failure to rewrite in coercions & kinds leads to spurious occurscheck ...20210408T08:48:53ZRichard Eisenbergrae@richarde.devGHC's failure to rewrite in coercions & kinds leads to spurious occurscheck failureConsider this mess:
```hs
{# LANGUAGE ExplicitForAll, PolyKinds, DataKinds, TypeFamilies,
StandaloneKindSignatures, AllowAmbiguousTypes, GADTs,
TypeOperators #}
module Bug where
import Data.Kind ( Type )
import Data.Type.Equality ( type (~~) )
import Data.Proxy ( Proxy )
type Const :: () > k1 > k2 > k1
type family Const u x y where
Const '() x y = x
type Equals :: k1 > k2 > Type
type family Equals a b where
Equals a a = Char
Equals a b = Bool
type IsUnit :: () > Type
data IsUnit u where
ItIs :: IsUnit '()
f :: forall (u :: ()) (a :: Type) (b :: Const u Type a). (a ~~ b)
=> IsUnit u > a > Proxy b > Equals a b
f ItIs _ _ = 'x'
g = f ItIs
```
GHC fails (in the RHS of `g`) with an occurscheck, but it should succeed.
The problem is that we end up with
```
[W] (alpha :: Type) ~# (beta :: Const upsilon Type alpha)
```
where we have already unified `upsilon := '()`.
But GHC refuses to rewrite in kinds, so the `Const` never reduces, and we reject the program. Note that a solution exists, with `alpha := Any @Type` and `beta := Any @Type > sym (AxConst Type (Any @Type))`.
Proposed solution:
The wanted above actually gets simplified to become
```
[W] co :: Const '() Type alpha ~# Type
[W] w2 :: (alpha :: Type) ~# ((beta > co) :: Type)
```
The `co` is easily solved. Then, when we get to `w2`, we are in Wrinkle (3) of Note [Equalities with incompatible kinds]. Happily, we should be able to detect that `alpha` is free in `co` and reorient, giving
```
[W] w3 :: (beta :: Const '() Type alpha) ~# (alpha > sym co :: Const '() Type alpha)
```
which can be solved by unifying `beta := alpha > sym co`. `alpha` will then remain unconstrained and will be zonked to `Any`.
The key new part is looking at the coercion when deciding whether to reorient.Consider this mess:
```hs
{# LANGUAGE ExplicitForAll, PolyKinds, DataKinds, TypeFamilies,
StandaloneKindSignatures, AllowAmbiguousTypes, GADTs,
TypeOperators #}
module Bug where
import Data.Kind ( Type )
import Data.Type.Equality ( type (~~) )
import Data.Proxy ( Proxy )
type Const :: () > k1 > k2 > k1
type family Const u x y where
Const '() x y = x
type Equals :: k1 > k2 > Type
type family Equals a b where
Equals a a = Char
Equals a b = Bool
type IsUnit :: () > Type
data IsUnit u where
ItIs :: IsUnit '()
f :: forall (u :: ()) (a :: Type) (b :: Const u Type a). (a ~~ b)
=> IsUnit u > a > Proxy b > Equals a b
f ItIs _ _ = 'x'
g = f ItIs
```
GHC fails (in the RHS of `g`) with an occurscheck, but it should succeed.
The problem is that we end up with
```
[W] (alpha :: Type) ~# (beta :: Const upsilon Type alpha)
```
where we have already unified `upsilon := '()`.
But GHC refuses to rewrite in kinds, so the `Const` never reduces, and we reject the program. Note that a solution exists, with `alpha := Any @Type` and `beta := Any @Type > sym (AxConst Type (Any @Type))`.
Proposed solution:
The wanted above actually gets simplified to become
```
[W] co :: Const '() Type alpha ~# Type
[W] w2 :: (alpha :: Type) ~# ((beta > co) :: Type)
```
The `co` is easily solved. Then, when we get to `w2`, we are in Wrinkle (3) of Note [Equalities with incompatible kinds]. Happily, we should be able to detect that `alpha` is free in `co` and reorient, giving
```
[W] w3 :: (beta :: Const '() Type alpha) ~# (alpha > sym co :: Const '() Type alpha)
```
which can be solved by unifying `beta := alpha > sym co`. `alpha` will then remain unconstrained and will be zonked to `Any`.
The key new part is looking at the coercion when deciding whether to reorient.Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/19675runExists: a typelevel version of runRW20210409T20:55:20ZSimon Peyton JonesrunExists: a typelevel version of runRW(All this started in #16646.)
# Problem
In GHC.TypeLits we have
```
newtype SSymbol (s :: Symbol) = SSymbol String
```
The intent is that this type is very private to GHC.TypeLits, beucase
it is supposed to be a singleton type. If we have two values `x1, x2
:: SSymbol ty`, then the string inside `x1` should be the same as the
string inside `x2`.
How do we make a `SSymbol`? We want to provide
```
withSSymbol :: String > (forall s. SSymbol s > r) > r
```
Note the `forall s`, which plays a similar (existential) role to the `forall s` in
```
runST :: (forall s. ST s a) > a
```
But how can we *define* `withSSymbol`? Here is a try:
```
withSSymbol str cont = cont (SSymbol str)
```
But if we elaborate we find this means:
```
withSSymbol str cont = cont @(Any @Symbol) (SSymbol @(Any @Symbol) str)
```
What is that `Any`??? And consider
```
withSSymbol "foo" (\s1 > withSSymbol "bar2 (\s2 > blah)
```
If we allow `withSSymbol` to inline we can get
```
let s1 = SSymbol @(Any @Symbol) "foo"
s2 = SSymbol @(Any @Symbol) "bar"
in blah
```
Urk! `s1, s2 :: SSymbol (Any @Symbol)` but they carry different payloads.
In conjunction with `magicDict` this can give rise to subtle outright bugs:
see #16586 and `Note [NOINLINE someNatVal]` in GHC.TypeNats.
The hacky "solution" (adopted by the patch for #16586) is "don't
inline `withSSymbol`" but that is smelly  and inefficient!
# Solution
So what can we do? Here is one suggestion. Suppose we had
```
runExists :: forall k. (forall (a::k). Proxy# @k a > r) > r
```
Rather like `runST`, this gives you a type variable you can refer to, that is effectively existential.
Now we can write
```
withSSymbol str cont = runExists (\(_::Proxy# s) > cont (SSymbol @s str))
```
So `runExists` allows us to bring into scope a fresh skolem type variable.
**Note 1:** If we had biglambda in the source language, as Richard wants, maybe we could even get rid of the `Proxy#`
and write
```
runExists :: forall k. (forall (a::k). r) > r
withSSymbol str cont = runExists (\@s > cont (SSymbol @s str))
```
which would be quite a bit nicer. **End of note 1**
We already have something very like `runExists`, in the form of `runRW#`
```
runRW# :: forall (r :: RuntimeRep) (o :: TYPE r).
(State# RealWorld > o) > o
 See Note [runRW magic] in GHC.CoreToStg.Prep.
{# NOINLINE runRW# #}  runRW# is inlined manually in CorePrep
runRW# m = m realWorld#
```
where `Note [runRW magic]` in GHC.CoreToStg.Prep (reproduced below) describes various bit of magic are described that allow us to optimise around `runRW`. In particular:
* case expressions move inside the argument
* we inline `runRW#` in CorePrep, to eliminate the lambda.
We could do the same for `runExists`.
The advantage of this is that *we don't need any NOINLINE stuff for `withSSymbol` and friends*.
Only `runExists` is magic.
**Note 2.** Actually we'd want `runExists to have a levitypolymorphic result, thus:
```
runExists :: forall k (r :: RuntimeRep) (o :: TYPE r).
(forall (a::k). o) > o
```
**End of Note2**.
Question: can we somehow combine `runRW#` and `runExists`? I think they may be a bit different:
* `runExists` brings a new skolem type variable into scope
* `runRW` brings a valuelevel token into scope  it's a *value* lambda
## Note [runRW magic]
Reproduced from GHC.CoreToStg.Prep
```
{ Note [runRW magic]
~~~~~~~~~~~~~~~~~~~~~
Some definitions, for instance @runST@, must have careful control over float out
of the bindings in their body. Consider this use of @runST@,
f x = runST ( \ s > let (a, s') = newArray# 100 [] s
(_, s'') = fill_in_array_or_something a x s'
in freezeArray# a s'' )
If we inline @runST@, we'll get:
f x = let (a, s') = newArray# 100 [] realWorld#{NB}
(_, s'') = fill_in_array_or_something a x s'
in freezeArray# a s''
And now if we allow the @newArray#@ binding to float out to become a CAF,
we end up with a result that is totally and utterly wrong:
f = let (a, s') = newArray# 100 [] realWorld#{NB}  YIKES!!!
in \ x >
let (_, s'') = fill_in_array_or_something a x s'
in freezeArray# a s''
All calls to @f@ will share a {\em single} array! Clearly this is nonsense and
must be prevented.
This is what @runRW#@ gives us: by being inlined extremely late in the
optimization (right before lowering to STG, in CorePrep), we can ensure that
no further floating will occur. This allows us to safely inline things like
@runST@, which are otherwise needlessly expensive (see #10678 and #5916).
'runRW' has a variety of quirks:
* 'runRW' is knownkey with a NOINLINE definition in
GHC.Magic. This definition is used in cases where runRW is curried.
* In addition to its normal Haskell definition in GHC.Magic, we give it
a special late inlining here in CorePrep and GHC.StgToByteCode, avoiding
the incorrect sharing due to floatout noted above.
* It is levitypolymorphic:
runRW# :: forall (r1 :: RuntimeRep). (o :: TYPE r)
=> (State# RealWorld > (# State# RealWorld, o #))
> (# State# RealWorld, o #)
* It has some special simplification logic to allow unboxing of results when
runRW# appears in a strict context. See Note [Simplification of runRW#]
below.
* Since its body is inlined, we allow runRW#'s argument to contain jumps to
join points. That is, the following is allowed:
join j x = ...
in runRW# @_ @_ (\s > ... jump j 42 ...)
The Core Linter knows about this. See Note [Linting of runRW#] in
GHC.Core.Lint for details.
The occurrence analyser and SetLevels also know about this, as described in
Note [Simplification of runRW#].
Other relevant Notes:
* Note [Simplification of runRW#] below, describing a transformation of runRW
applications in strict contexts performed by the simplifier.
* Note [Linting of runRW#] in GHC.Core.Lint
* Note [runRW arg] below, describing a nonobvious case where the
lateinlining could go wrong.
```(All this started in #16646.)
# Problem
In GHC.TypeLits we have
```
newtype SSymbol (s :: Symbol) = SSymbol String
```
The intent is that this type is very private to GHC.TypeLits, beucase
it is supposed to be a singleton type. If we have two values `x1, x2
:: SSymbol ty`, then the string inside `x1` should be the same as the
string inside `x2`.
How do we make a `SSymbol`? We want to provide
```
withSSymbol :: String > (forall s. SSymbol s > r) > r
```
Note the `forall s`, which plays a similar (existential) role to the `forall s` in
```
runST :: (forall s. ST s a) > a
```
But how can we *define* `withSSymbol`? Here is a try:
```
withSSymbol str cont = cont (SSymbol str)
```
But if we elaborate we find this means:
```
withSSymbol str cont = cont @(Any @Symbol) (SSymbol @(Any @Symbol) str)
```
What is that `Any`??? And consider
```
withSSymbol "foo" (\s1 > withSSymbol "bar2 (\s2 > blah)
```
If we allow `withSSymbol` to inline we can get
```
let s1 = SSymbol @(Any @Symbol) "foo"
s2 = SSymbol @(Any @Symbol) "bar"
in blah
```
Urk! `s1, s2 :: SSymbol (Any @Symbol)` but they carry different payloads.
In conjunction with `magicDict` this can give rise to subtle outright bugs:
see #16586 and `Note [NOINLINE someNatVal]` in GHC.TypeNats.
The hacky "solution" (adopted by the patch for #16586) is "don't
inline `withSSymbol`" but that is smelly  and inefficient!
# Solution
So what can we do? Here is one suggestion. Suppose we had
```
runExists :: forall k. (forall (a::k). Proxy# @k a > r) > r
```
Rather like `runST`, this gives you a type variable you can refer to, that is effectively existential.
Now we can write
```
withSSymbol str cont = runExists (\(_::Proxy# s) > cont (SSymbol @s str))
```
So `runExists` allows us to bring into scope a fresh skolem type variable.
**Note 1:** If we had biglambda in the source language, as Richard wants, maybe we could even get rid of the `Proxy#`
and write
```
runExists :: forall k. (forall (a::k). r) > r
withSSymbol str cont = runExists (\@s > cont (SSymbol @s str))
```
which would be quite a bit nicer. **End of note 1**
We already have something very like `runExists`, in the form of `runRW#`
```
runRW# :: forall (r :: RuntimeRep) (o :: TYPE r).
(State# RealWorld > o) > o
 See Note [runRW magic] in GHC.CoreToStg.Prep.
{# NOINLINE runRW# #}  runRW# is inlined manually in CorePrep
runRW# m = m realWorld#
```
where `Note [runRW magic]` in GHC.CoreToStg.Prep (reproduced below) describes various bit of magic are described that allow us to optimise around `runRW`. In particular:
* case expressions move inside the argument
* we inline `runRW#` in CorePrep, to eliminate the lambda.
We could do the same for `runExists`.
The advantage of this is that *we don't need any NOINLINE stuff for `withSSymbol` and friends*.
Only `runExists` is magic.
**Note 2.** Actually we'd want `runExists to have a levitypolymorphic result, thus:
```
runExists :: forall k (r :: RuntimeRep) (o :: TYPE r).
(forall (a::k). o) > o
```
**End of Note2**.
Question: can we somehow combine `runRW#` and `runExists`? I think they may be a bit different:
* `runExists` brings a new skolem type variable into scope
* `runRW` brings a valuelevel token into scope  it's a *value* lambda
## Note [runRW magic]
Reproduced from GHC.CoreToStg.Prep
```
{ Note [runRW magic]
~~~~~~~~~~~~~~~~~~~~~
Some definitions, for instance @runST@, must have careful control over float out
of the bindings in their body. Consider this use of @runST@,
f x = runST ( \ s > let (a, s') = newArray# 100 [] s
(_, s'') = fill_in_array_or_something a x s'
in freezeArray# a s'' )
If we inline @runST@, we'll get:
f x = let (a, s') = newArray# 100 [] realWorld#{NB}
(_, s'') = fill_in_array_or_something a x s'
in freezeArray# a s''
And now if we allow the @newArray#@ binding to float out to become a CAF,
we end up with a result that is totally and utterly wrong:
f = let (a, s') = newArray# 100 [] realWorld#{NB}  YIKES!!!
in \ x >
let (_, s'') = fill_in_array_or_something a x s'
in freezeArray# a s''
All calls to @f@ will share a {\em single} array! Clearly this is nonsense and
must be prevented.
This is what @runRW#@ gives us: by being inlined extremely late in the
optimization (right before lowering to STG, in CorePrep), we can ensure that
no further floating will occur. This allows us to safely inline things like
@runST@, which are otherwise needlessly expensive (see #10678 and #5916).
'runRW' has a variety of quirks:
* 'runRW' is knownkey with a NOINLINE definition in
GHC.Magic. This definition is used in cases where runRW is curried.
* In addition to its normal Haskell definition in GHC.Magic, we give it
a special late inlining here in CorePrep and GHC.StgToByteCode, avoiding
the incorrect sharing due to floatout noted above.
* It is levitypolymorphic:
runRW# :: forall (r1 :: RuntimeRep). (o :: TYPE r)
=> (State# RealWorld > (# State# RealWorld, o #))
> (# State# RealWorld, o #)
* It has some special simplification logic to allow unboxing of results when
runRW# appears in a strict context. See Note [Simplification of runRW#]
below.
* Since its body is inlined, we allow runRW#'s argument to contain jumps to
join points. That is, the following is allowed:
join j x = ...
in runRW# @_ @_ (\s > ... jump j 42 ...)
The Core Linter knows about this. See Note [Linting of runRW#] in
GHC.Core.Lint for details.
The occurrence analyser and SetLevels also know about this, as described in
Note [Simplification of runRW#].
Other relevant Notes:
* Note [Simplification of runRW#] below, describing a transformation of runRW
applications in strict contexts performed by the simplifier.
* Note [Linting of runRW#] in GHC.Core.Lint
* Note [runRW arg] below, describing a nonobvious case where the
lateinlining could go wrong.
```https://gitlab.haskell.org/ghc/ghc//issues/19677GHC does not rewrite in FunTy20210412T15:42:16ZRichard Eisenbergrae@richarde.devGHC does not rewrite in FunTyConsider
```hs
{# LANGUAGE ExplicitForAll, PolyKinds, DataKinds, TypeFamilies, GADTs #}
module Bug where
import GHC.Exts
class C x where
meth :: x > ()
instance C (a > b) where
meth _ = ()
type family Lifty throttle where
Lifty Int = LiftedRep
data G a where
MkG :: G Int
foo :: forall i (a :: TYPE (Lifty i)) (b :: TYPE (Lifty i)). G i > (a > b) > ()
foo MkG = meth
```
GHC rejects, saying it cannot find an instance for `C (a > b)`. But it should accept.
The problem is that the kinds of `a` and `b` are `TYPE (Lifty i)`. Even if we know `i ~ Int`, and therefore that `Lifty i ~ LiftedRep`, GHC does not rewrite these kinds internally, allowing instance matching to succeed.
!2477, when complete, should address this.Consider
```hs
{# LANGUAGE ExplicitForAll, PolyKinds, DataKinds, TypeFamilies, GADTs #}
module Bug where
import GHC.Exts
class C x where
meth :: x > ()
instance C (a > b) where
meth _ = ()
type family Lifty throttle where
Lifty Int = LiftedRep
data G a where
MkG :: G Int
foo :: forall i (a :: TYPE (Lifty i)) (b :: TYPE (Lifty i)). G i > (a > b) > ()
foo MkG = meth
```
GHC rejects, saying it cannot find an instance for `C (a > b)`. But it should accept.
The problem is that the kinds of `a` and `b` are `TYPE (Lifty i)`. Even if we know `i ~ Int`, and therefore that `Lifty i ~ LiftedRep`, GHC does not rewrite these kinds internally, allowing instance matching to succeed.
!2477, when complete, should address this.Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/19682Constraint solver regression in 9.220210726T02:26:19ZAndres LöhConstraint solver regression in 9.2## Summary
While trying to make the `genericssop` and `sopcore` packages compatible with GHC 9.2, I discovered a regression in the constraint solver. The included program compiles at with GHC 9.0.1, GHC 8.8.4, GHC 8.6.5, GHC 8.4.4, GHC 8.2.2, but it fails with GHC 9.2 with the following error message:
```
AllEq.hs:19:21: error:
• Couldn't match type ‘ys0’ with ‘Head ys0 : Tail ys0’
arising from a use of ‘convert’
• In the second argument of ‘const’, namely ‘(convert xs)’
In the expression: const () (convert xs)
In an equation for ‘test’: test xs = const () (convert xs)

19  test xs = const () (convert xs)
 ^^^^^^^
```
## Steps to reproduce
Run `ghc` or `ghci` on the following file:
```haskell
{# LANGUAGE DataKinds #}
{# LANGUAGE FlexibleInstances #}
{# LANGUAGE MultiParamTypeClasses #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE TypeOperators #}
{# LANGUAGE UndecidableInstances #}
{# LANGUAGE UndecidableSuperClasses #}
module AllEq where
import Data.Kind
import Data.Proxy
convert :: (AllEq xs ys) => Proxy xs > Proxy ys
convert p = Proxy
 Works with ghc up to 9.0. Fails with ghc 9.2.
test :: Proxy '[Char, Bool] > ()
test xs = const () (convert xs)
class (AllEqF xs ys, SameShapeAs xs ys) => AllEq (xs :: [a]) (ys :: [a])
instance (AllEqF xs ys, SameShapeAs xs ys) => AllEq xs ys
type family SameShapeAs (xs :: [a]) (ys :: [a]) :: Constraint where
SameShapeAs '[] ys = (ys ~ '[])
SameShapeAs (x : xs) ys = (ys ~ (Head ys : Tail ys))
type family AllEqF (xs :: [a]) (ys :: [a]) :: Constraint where
AllEqF '[] '[] = ()
AllEqF (x : xs) (y : ys) = (x ~ y, AllEq xs ys)
type family Head (xs :: [a]) :: a where
Head (x : xs) = x
type family Tail (xs :: [a]) :: [a] where
Tail (x : xs) = xs
```
## Expected behavior
I would expect the program to be accepted.
## Environment
* GHC version used: 9.2.0.20210406, built locally on my machine from the `ghc9.2` branch at commit d197fb3d5c053cfb526272c29a443c33d1af0980
Optional:
* Operating System: Linux (NixOS)
* System Architecture: x86_64## Summary
While trying to make the `genericssop` and `sopcore` packages compatible with GHC 9.2, I discovered a regression in the constraint solver. The included program compiles at with GHC 9.0.1, GHC 8.8.4, GHC 8.6.5, GHC 8.4.4, GHC 8.2.2, but it fails with GHC 9.2 with the following error message:
```
AllEq.hs:19:21: error:
• Couldn't match type ‘ys0’ with ‘Head ys0 : Tail ys0’
arising from a use of ‘convert’
• In the second argument of ‘const’, namely ‘(convert xs)’
In the expression: const () (convert xs)
In an equation for ‘test’: test xs = const () (convert xs)

19  test xs = const () (convert xs)
 ^^^^^^^
```
## Steps to reproduce
Run `ghc` or `ghci` on the following file:
```haskell
{# LANGUAGE DataKinds #}
{# LANGUAGE FlexibleInstances #}
{# LANGUAGE MultiParamTypeClasses #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE TypeOperators #}
{# LANGUAGE UndecidableInstances #}
{# LANGUAGE UndecidableSuperClasses #}
module AllEq where
import Data.Kind
import Data.Proxy
convert :: (AllEq xs ys) => Proxy xs > Proxy ys
convert p = Proxy
 Works with ghc up to 9.0. Fails with ghc 9.2.
test :: Proxy '[Char, Bool] > ()
test xs = const () (convert xs)
class (AllEqF xs ys, SameShapeAs xs ys) => AllEq (xs :: [a]) (ys :: [a])
instance (AllEqF xs ys, SameShapeAs xs ys) => AllEq xs ys
type family SameShapeAs (xs :: [a]) (ys :: [a]) :: Constraint where
SameShapeAs '[] ys = (ys ~ '[])
SameShapeAs (x : xs) ys = (ys ~ (Head ys : Tail ys))
type family AllEqF (xs :: [a]) (ys :: [a]) :: Constraint where
AllEqF '[] '[] = ()
AllEqF (x : xs) (y : ys) = (x ~ y, AllEq xs ys)
type family Head (xs :: [a]) :: a where
Head (x : xs) = x
type family Tail (xs :: [a]) :: [a] where
Tail (x : xs) = xs
```
## Expected behavior
I would expect the program to be accepted.
## Environment
* GHC version used: 9.2.0.20210406, built locally on my machine from the `ghc9.2` branch at commit d197fb3d5c053cfb526272c29a443c33d1af0980
Optional:
* Operating System: Linux (NixOS)
* System Architecture: x86_649.2.1https://gitlab.haskell.org/ghc/ghc//issues/19690Bottom dictionaries can be derived with QuantifiedConstraints, UndecidableIns...20210416T00:27:00ZaadaafgtaaBottom dictionaries can be derived with QuantifiedConstraints, UndecidableInstances and UndecidableSuperClasses[I'm not sure if this is a bug or documentation issue. I'd prefer the former so I applied "bug" template]
## Summary
With `QuantifiedConstraints`, `UndecidableInstances` and `UndecidableSuperClasses` it is possible to
produce bottom dictionary, which isn't mentioned in docs as far as I can see.
## Steps to reproduce
```haskell
{# LANGUAGE UndecidableInstances, UndecidableSuperClasses, ConstraintKinds, FlexibleInstances,
GADTs, QuantifiedConstraints, TypeApplications, ScopedTypeVariables #}
module QCLoop where
class c => Hold c
instance c => Hold c
data Dict c = c => Dict
anythingDict :: Dict c
anythingDict = go
where
go :: (Hold c => c) => Dict c
go = Dict
```
Produces bottom dictionary
```haskell
Rec {
$dHold_rxi :: forall {c :: Constraint}. Hold c
$dHold_rxi = $dHold_rxi
end Rec }
anythingDict :: forall (c :: Constraint). Dict c
anythingDict = \ (@c) > Dict ($dHold_rxi `cast` <Co:2>)
```
## Expected behavior
Either the program is rejected with "could not deduce c" or "too many iterations", or documentation for
`UndecidableInstances` and/or `UndecidableSuperClasses` mentions that they may result in
nontermination not only in typechecker but also at runtime.
I would really prefer the former as the ability to "prove" anything with such code scares me a bit.
## Environment
* GHC version used: 8.10.4, 9.0.1 and 9.1.20210409
* Operating System: Linux (NixOS)
* System Architecture: x8664[I'm not sure if this is a bug or documentation issue. I'd prefer the former so I applied "bug" template]
## Summary
With `QuantifiedConstraints`, `UndecidableInstances` and `UndecidableSuperClasses` it is possible to
produce bottom dictionary, which isn't mentioned in docs as far as I can see.
## Steps to reproduce
```haskell
{# LANGUAGE UndecidableInstances, UndecidableSuperClasses, ConstraintKinds, FlexibleInstances,
GADTs, QuantifiedConstraints, TypeApplications, ScopedTypeVariables #}
module QCLoop where
class c => Hold c
instance c => Hold c
data Dict c = c => Dict
anythingDict :: Dict c
anythingDict = go
where
go :: (Hold c => c) => Dict c
go = Dict
```
Produces bottom dictionary
```haskell
Rec {
$dHold_rxi :: forall {c :: Constraint}. Hold c
$dHold_rxi = $dHold_rxi
end Rec }
anythingDict :: forall (c :: Constraint). Dict c
anythingDict = \ (@c) > Dict ($dHold_rxi `cast` <Co:2>)
```
## Expected behavior
Either the program is rejected with "could not deduce c" or "too many iterations", or documentation for
`UndecidableInstances` and/or `UndecidableSuperClasses` mentions that they may result in
nontermination not only in typechecker but also at runtime.
I would really prefer the former as the ability to "prove" anything with such code scares me a bit.
## Environment
* GHC version used: 8.10.4, 9.0.1 and 9.1.20210409
* Operating System: Linux (NixOS)
* System Architecture: x8664https://gitlab.haskell.org/ghc/ghc//issues/19726Unexpected typechecking behavior with let and DataKinds20210510T12:28:34ZbenjaminUnexpected typechecking behavior with let and DataKinds## Motivation
When playing around with the code for knownlength vectors from #19722, I noticed following behavior in the typechecker when trying to implement a function to get the last element of a vector.
```
last :: Vec (Succ n) a > a
last (x :> Nil) = x
last (_ :> xs) = case xs of x' :> xs' > last xs
last (_ :> xs) = let (x' :> xs') = xs in last xs
last (_ :> xs) = let (x' :> xs') = xs in last (x' :> xs')
```
The main issue here is that we can't just write `last (_ :> xs) = last xs`, because then GHC can't verify that the type of `xs` is really `Vec (Succ n) a`.
So the workaround is to let GHC know that `xs` is really nonempty in this second case.
The first version of the case `_ :> xs` using a caseexpression compiles fine, but the two version implemented using letexpressions don't typecheck.
I lack an indepth understanding of the typechecker or even the DataKinds extension, but I think the 3 versions are semantically identical.
## Proposal
Make all 3 versions typecheck.## Motivation
When playing around with the code for knownlength vectors from #19722, I noticed following behavior in the typechecker when trying to implement a function to get the last element of a vector.
```
last :: Vec (Succ n) a > a
last (x :> Nil) = x
last (_ :> xs) = case xs of x' :> xs' > last xs
last (_ :> xs) = let (x' :> xs') = xs in last xs
last (_ :> xs) = let (x' :> xs') = xs in last (x' :> xs')
```
The main issue here is that we can't just write `last (_ :> xs) = last xs`, because then GHC can't verify that the type of `xs` is really `Vec (Succ n) a`.
So the workaround is to let GHC know that `xs` is really nonempty in this second case.
The first version of the case `_ :> xs` using a caseexpression compiles fine, but the two version implemented using letexpressions don't typecheck.
I lack an indepth understanding of the typechecker or even the DataKinds extension, but I think the 3 versions are semantically identical.
## Proposal
Make all 3 versions typecheck.https://gitlab.haskell.org/ghc/ghc//issues/19765Inscope check for type variables can be confusing in presence of runtime rep...20210429T12:41:33ZRichard Eisenbergrae@richarde.devInscope check for type variables can be confusing in presence of runtime representation polymorphismFrom #19764, thanks to @yaitskov:
```hs
{# LANGUAGE DeriveLift #}
{# LANGUAGE StandaloneDeriving #}
module Main where
import Language.Haskell.TH.Syntax (Lift (..))
newtype Ref = Ref { r :: ()} deriving (Lift)
deriving instance Lift ()
main :: IO ()
main = pure ()
```
This prints
```
/Users/rae/temp/Bug.hs:8:41: error:
• Overlapping instances for Lift ()
arising from the first field of ‘Ref’ (type ‘()’)
Matching instances:
two instances involving outofscope types
(use fprintpotentialinstances to see them all)
• When deriving the instance for (Lift Ref)

8  newtype Ref = Ref { r :: ()} deriving (Lift)

```
The "instances involving outofscope types" are both `Lift ()`. Note that `Lift` is in scope. So GHC must be confused about `()`, which is a shame.From #19764, thanks to @yaitskov:
```hs
{# LANGUAGE DeriveLift #}
{# LANGUAGE StandaloneDeriving #}
module Main where
import Language.Haskell.TH.Syntax (Lift (..))
newtype Ref = Ref { r :: ()} deriving (Lift)
deriving instance Lift ()
main :: IO ()
main = pure ()
```
This prints
```
/Users/rae/temp/Bug.hs:8:41: error:
• Overlapping instances for Lift ()
arising from the first field of ‘Ref’ (type ‘()’)
Matching instances:
two instances involving outofscope types
(use fprintpotentialinstances to see them all)
• When deriving the instance for (Lift Ref)

8  newtype Ref = Ref { r :: ()} deriving (Lift)

```
The "instances involving outofscope types" are both `Lift ()`. Note that `Lift` is in scope. So GHC must be confused about `()`, which is a shame.https://gitlab.haskell.org/ghc/ghc//issues/19787Weird behaviour with `tcIfaceExpr`20210503T17:41:43ZJosh MeredithWeird behaviour with `tcIfaceExpr`When recovering the Core AST of a class method in a plugin through multiple methods, the typecheck loaded (deserialised) AST appears to be using the wrong expression for certain methods. This occurs both using ASTs recovered from the preexisting unfoldings, as well as when using the `toIfaceBind` and `tcIfaceExpr` functions from GHC to (de)serialise the bindings via an extensible interface field.
As an example, using the following type class and instances:
```haskell
class TwoClass a where
twoA :: a > Integer
twoB :: a > Bool
instance TwoClass Integer where
twoA = id
twoB = (>1)
instance TwoClass Bool where
twoA True = 1
twoA False = 0
twoB = not
```
_Before_ serialisation, from the `CgGuts.cgBinds`, we have class methods that look like:
```
twoA :: forall a. TwoClass a => a > Integer
[GblId[ClassOp],
Arity=1,
Caf=NoCafRefs,
Str=<SP(SL,A)>,
RULES: Built in rule for twoA: "Class op twoA"]
twoA
= \ (@a) (v_B1 :: TwoClass a) >
case v_B1 of v_B1 { C:TwoClass v_B2 v_B3 > v_B2 },
twoB :: forall a. TwoClass a => a > Bool
[GblId[ClassOp],
Arity=1,
Caf=NoCafRefs,
Str=<SP(A,SL)>,
RULES: Built in rule for twoB: "Class op twoB"]
twoB
= \ (@a) (v_B1 :: TwoClass a) >
case v_B1 of v_B1 { C:TwoClass v_B2 v_B3 > v_B3 }
```
Each of the class methods is deconstructed as a data constructor and obviously uses the correct field of that constructor as the method. However, after roundtripping this through (de)serialisation, we're have:
```
twoA :: forall a. TwoClass a => a > Integer
[LclId]
twoA
= \ (@a) (v :: TwoClass a) > case v of v { C:TwoClass v v > v },
twoB :: forall a. TwoClass a => a > Bool
[LclId]
twoB
= \ (@a) (v :: TwoClass a) > case v of v { C:TwoClass v v > v }
```
Now, the reuse of the variable name `v` shouldn't be a problem on it's own  since these local variables are serialised as `FastStrings`, which have `Unique`s  but we find in the plugin that for `twoA`, it's the _wrong_ `Unique`, incorrectly giving `twoA` an expression of type `a > Bool`.
We're using GHC 8.10.4 for the Plutus plugin, but I've tested and found what seems to be the same behaviour in an uptodate version of master. I expect that there must be another explanation here, since unfoldings are used by GHC for inlining, and I don't believe those would go unnoticed if broken.When recovering the Core AST of a class method in a plugin through multiple methods, the typecheck loaded (deserialised) AST appears to be using the wrong expression for certain methods. This occurs both using ASTs recovered from the preexisting unfoldings, as well as when using the `toIfaceBind` and `tcIfaceExpr` functions from GHC to (de)serialise the bindings via an extensible interface field.
As an example, using the following type class and instances:
```haskell
class TwoClass a where
twoA :: a > Integer
twoB :: a > Bool
instance TwoClass Integer where
twoA = id
twoB = (>1)
instance TwoClass Bool where
twoA True = 1
twoA False = 0
twoB = not
```
_Before_ serialisation, from the `CgGuts.cgBinds`, we have class methods that look like:
```
twoA :: forall a. TwoClass a => a > Integer
[GblId[ClassOp],
Arity=1,
Caf=NoCafRefs,
Str=<SP(SL,A)>,
RULES: Built in rule for twoA: "Class op twoA"]
twoA
= \ (@a) (v_B1 :: TwoClass a) >
case v_B1 of v_B1 { C:TwoClass v_B2 v_B3 > v_B2 },
twoB :: forall a. TwoClass a => a > Bool
[GblId[ClassOp],
Arity=1,
Caf=NoCafRefs,
Str=<SP(A,SL)>,
RULES: Built in rule for twoB: "Class op twoB"]
twoB
= \ (@a) (v_B1 :: TwoClass a) >
case v_B1 of v_B1 { C:TwoClass v_B2 v_B3 > v_B3 }
```
Each of the class methods is deconstructed as a data constructor and obviously uses the correct field of that constructor as the method. However, after roundtripping this through (de)serialisation, we're have:
```
twoA :: forall a. TwoClass a => a > Integer
[LclId]
twoA
= \ (@a) (v :: TwoClass a) > case v of v { C:TwoClass v v > v },
twoB :: forall a. TwoClass a => a > Bool
[LclId]
twoB
= \ (@a) (v :: TwoClass a) > case v of v { C:TwoClass v v > v }
```
Now, the reuse of the variable name `v` shouldn't be a problem on it's own  since these local variables are serialised as `FastStrings`, which have `Unique`s  but we find in the plugin that for `twoA`, it's the _wrong_ `Unique`, incorrectly giving `twoA` an expression of type `a > Bool`.
We're using GHC 8.10.4 for the Plutus plugin, but I've tested and found what seems to be the same behaviour in an uptodate version of master. I expect that there must be another explanation here, since unfoldings are used by GHC for inlining, and I don't believe those would go unnoticed if broken.https://gitlab.haskell.org/ghc/ghc//issues/19815Use isReflexiveCo when building an MCo20210511T03:26:51ZSimon Peyton JonesUse isReflexiveCo when building an MCoIn other work I found that checking for reflexivity (using `isReflexiveCo` rather than `isReflCo`) when building an MCoercion had an astonishing impact on T18223. Compile time allocation reduced by a factor of four!
This tickets is to check whether it's a good idea generally.In other work I found that checking for reflexivity (using `isReflexiveCo` rather than `isReflCo`) when building an MCoercion had an astonishing impact on T18223. Compile time allocation reduced by a factor of four!
This tickets is to check whether it's a good idea generally.https://gitlab.haskell.org/ghc/ghc//issues/19847Type application in pattern does not substitute correctly20210624T21:01:46ZRichard Eisenbergrae@richarde.devType application in pattern does not substitute correctlyInspired by @Icelandjack's https://gitlab.haskell.org/ghc/ghc//issues/19691#note_352594, I typed in
```hs
pattern Is :: forall (b :: Type) (a :: Type). Typeable b => (a ~ b) => TypeRep a
pattern Is < (eqTypeRep (typeRep @b) > Just HRefl)
where Is = typeRep
def :: TypeRep a > a
def = \case
Is @Int > 10
Is @Bool > False
```
which looks pretty sensible to me. HEAD tells me
```
Scratch.hs:40:3: error:
• No instance for (Typeable b0) arising from a use of ‘Is’
• In the pattern: Is @Int
In a case alternative: Is @Int > 10
In the expression:
\case
Is @Int > 10
Is @Bool > False

40  Is @Int > 10
 ^^^^^^^
Scratch.hs:40:3: error:
• Could not deduce: a ~ Int
from the context: a ~ b0
bound by a pattern with pattern synonym:
Is :: forall b a. Typeable b => (a ~ b) => TypeRep a,
in a case alternative
at Scratch.hs:40:39
Expected: b0
Actual: Int
‘a’ is a rigid type variable bound by
the type signature for:
def :: forall a. TypeRep a > a
at Scratch.hs:38:121
• In the pattern: Is @Int
In a case alternative: Is @Int > 10
In the expression:
\case
Is @Int > 10
Is @Bool > False
• Relevant bindings include
def :: TypeRep a > a (bound at Scratch.hs:39:1)

40  Is @Int > 10
 ^^^^^^^
Scratch.hs:41:3: error:
• No instance for (Typeable b1) arising from a use of ‘Is’
• In the pattern: Is @Bool
In a case alternative: Is @Bool > False
In the expression:
\case
Is @Int > 10
Is @Bool > False

41  Is @Bool > False
 ^^^^^^^^
Scratch.hs:41:15: error:
• Could not deduce: a ~ Bool
from the context: a ~ b1
bound by a pattern with pattern synonym:
Is :: forall b a. Typeable b => (a ~ b) => TypeRep a,
in a case alternative
at Scratch.hs:41:310
‘a’ is a rigid type variable bound by
the type signature for:
def :: forall a. TypeRep a > a
at Scratch.hs:38:121
• In the expression: False
In a case alternative: Is @Bool > False
In the expression:
\case
Is @Int > 10
Is @Bool > False
• Relevant bindings include
def :: TypeRep a > a (bound at Scratch.hs:39:1)

41  Is @Bool > False

```
But that looks wrong: it shouldn't be looking for `Typeable b0` or `Typeable b1`, it should be looking for `Typeable Int` or `Typeable Bool`. While I have not investigated further, this smells like a missing application of a substitution somewhere.Inspired by @Icelandjack's https://gitlab.haskell.org/ghc/ghc//issues/19691#note_352594, I typed in
```hs
pattern Is :: forall (b :: Type) (a :: Type). Typeable b => (a ~ b) => TypeRep a
pattern Is < (eqTypeRep (typeRep @b) > Just HRefl)
where Is = typeRep
def :: TypeRep a > a
def = \case
Is @Int > 10
Is @Bool > False
```
which looks pretty sensible to me. HEAD tells me
```
Scratch.hs:40:3: error:
• No instance for (Typeable b0) arising from a use of ‘Is’
• In the pattern: Is @Int
In a case alternative: Is @Int > 10
In the expression:
\case
Is @Int > 10
Is @Bool > False

40  Is @Int > 10
 ^^^^^^^
Scratch.hs:40:3: error:
• Could not deduce: a ~ Int
from the context: a ~ b0
bound by a pattern with pattern synonym:
Is :: forall b a. Typeable b => (a ~ b) => TypeRep a,
in a case alternative
at Scratch.hs:40:39
Expected: b0
Actual: Int
‘a’ is a rigid type variable bound by
the type signature for:
def :: forall a. TypeRep a > a
at Scratch.hs:38:121
• In the pattern: Is @Int
In a case alternative: Is @Int > 10
In the expression:
\case
Is @Int > 10
Is @Bool > False
• Relevant bindings include
def :: TypeRep a > a (bound at Scratch.hs:39:1)

40  Is @Int > 10
 ^^^^^^^
Scratch.hs:41:3: error:
• No instance for (Typeable b1) arising from a use of ‘Is’
• In the pattern: Is @Bool
In a case alternative: Is @Bool > False
In the expression:
\case
Is @Int > 10
Is @Bool > False

41  Is @Bool > False
 ^^^^^^^^
Scratch.hs:41:15: error:
• Could not deduce: a ~ Bool
from the context: a ~ b1
bound by a pattern with pattern synonym:
Is :: forall b a. Typeable b => (a ~ b) => TypeRep a,
in a case alternative
at Scratch.hs:41:310
‘a’ is a rigid type variable bound by
the type signature for:
def :: forall a. TypeRep a > a
at Scratch.hs:38:121
• In the expression: False
In a case alternative: Is @Bool > False
In the expression:
\case
Is @Int > 10
Is @Bool > False
• Relevant bindings include
def :: TypeRep a > a (bound at Scratch.hs:39:1)

41  Is @Bool > False

```
But that looks wrong: it shouldn't be looking for `Typeable b0` or `Typeable b1`, it should be looking for `Typeable Int` or `Typeable Bool`. While I have not investigated further, this smells like a missing application of a substitution somewhere.https://gitlab.haskell.org/ghc/ghc//issues/19855Wiredin names in hsboot files are not fully checked20210520T11:45:02ZSylvain HenryWiredin names in hsboot files are not fully checked#19638 was due to a declaration in a hsboot file of ghcbignum not matching the declaration in the corresponding hs file.
In https://gitlab.haskell.org/ghc/ghc//issues/19638#note_352989 @mpickering noticed that it is because wiredin names bypass some checks (see https://gitlab.haskell.org/ghc/ghc//blob/fc9546caf3e16db070bfc7bb5523c38595233e26/compiler/GHC/Tc/Module.hs#L870)
We should be more selective about the wiredin names that need this special treatment (which has been added in 5ad61e1470db6dbc8279569c5ad1cc093f753ac0).
Moreover the comment there says that it's used in particular for `GHC.Err.error` because it's a rather gross hack, but `libraries/base/GHC/Err.lhsboot` doesn't exist since 404327a9d9ce38804c5e407eaf2a4167e9a3c906 and `error` isn't wiredin since a7b751db766bd456ace4f76a861e5e8b927d8f17.#19638 was due to a declaration in a hsboot file of ghcbignum not matching the declaration in the corresponding hs file.
In https://gitlab.haskell.org/ghc/ghc//issues/19638#note_352989 @mpickering noticed that it is because wiredin names bypass some checks (see https://gitlab.haskell.org/ghc/ghc//blob/fc9546caf3e16db070bfc7bb5523c38595233e26/compiler/GHC/Tc/Module.hs#L870)
We should be more selective about the wiredin names that need this special treatment (which has been added in 5ad61e1470db6dbc8279569c5ad1cc093f753ac0).
Moreover the comment there says that it's used in particular for `GHC.Err.error` because it's a rather gross hack, but `libraries/base/GHC/Err.lhsboot` doesn't exist since 404327a9d9ce38804c5e407eaf2a4167e9a3c906 and `error` isn't wiredin since a7b751db766bd456ace4f76a861e5e8b927d8f17.https://gitlab.haskell.org/ghc/ghc//issues/19860Confusing error message: could not deduce from identical context20210519T14:09:17ZJaro ReindersConfusing error message: could not deduce from identical contextI am experimenting with compile time computation via typelevel programming. I wanted to try a more complicated function, namely `foldr`. The idea is to supply the first two arguments on the type level such that they are known statically at compile time. My reasoning is that this allows me to ensure that the resulting function of type `[a] > b` will be specialized and optimized for the `cons` and `nil` functions. I got to this code:
```haskell
{# LANGUAGE PolyKinds, ScopedTypeVariables, DataKinds, TemplateHaskell, TypeApplications, FlexibleContexts, AllowAmbiguousTypes, TypeOperators #}
module Main where
import Prelude.Singletons
import Data.Proxy
import Data.Reflection
foldr' :: forall a b (cons :: a ~> b ~> b) (nil :: b). Reifies (FoldrSym2 cons nil) ([a] > b) => [a] > b
foldr' = reflect (Proxy @(FoldrSym2 @_ @_ @[] cons nil))
```
For this code GHC gives the error:
```
app/Main.hs:16:10: error:
• Could not deduce (Reifies (FoldrSym2 cons nil) ([a] > b))
arising from a use of ‘reflect’
(maybe you haven't applied a function to enough arguments?)
from the context: Reifies (FoldrSym2 cons nil) ([a] > b)
bound by the type signature for:
foldr' :: forall {t :: * > *} a b (cons :: a ~> (b ~> b))
(nil :: b).
Reifies (FoldrSym2 cons nil) ([a] > b) =>
[a] > b
at app/Main.hs:15:1106
• In the expression:
reflect (Proxy @(FoldrSym2 @_ @_ @[] cons nil))
In an equation for ‘foldr'’:
foldr' = reflect (Proxy @(FoldrSym2 @_ @_ @[] cons nil))

16  foldr' = reflect (Proxy @(FoldrSym2 @_ @_ @[] cons nil))
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
This confuses me, for some reason GHC doesn't see that the context is equal to the required `Reifies` constraint, or perhaps there is some hidden information that prevents GHC from resolving that constraint.
This is with GHC 8.10.4I am experimenting with compile time computation via typelevel programming. I wanted to try a more complicated function, namely `foldr`. The idea is to supply the first two arguments on the type level such that they are known statically at compile time. My reasoning is that this allows me to ensure that the resulting function of type `[a] > b` will be specialized and optimized for the `cons` and `nil` functions. I got to this code:
```haskell
{# LANGUAGE PolyKinds, ScopedTypeVariables, DataKinds, TemplateHaskell, TypeApplications, FlexibleContexts, AllowAmbiguousTypes, TypeOperators #}
module Main where
import Prelude.Singletons
import Data.Proxy
import Data.Reflection
foldr' :: forall a b (cons :: a ~> b ~> b) (nil :: b). Reifies (FoldrSym2 cons nil) ([a] > b) => [a] > b
foldr' = reflect (Proxy @(FoldrSym2 @_ @_ @[] cons nil))
```
For this code GHC gives the error:
```
app/Main.hs:16:10: error:
• Could not deduce (Reifies (FoldrSym2 cons nil) ([a] > b))
arising from a use of ‘reflect’
(maybe you haven't applied a function to enough arguments?)
from the context: Reifies (FoldrSym2 cons nil) ([a] > b)
bound by the type signature for:
foldr' :: forall {t :: * > *} a b (cons :: a ~> (b ~> b))
(nil :: b).
Reifies (FoldrSym2 cons nil) ([a] > b) =>
[a] > b
at app/Main.hs:15:1106
• In the expression:
reflect (Proxy @(FoldrSym2 @_ @_ @[] cons nil))
In an equation for ‘foldr'’:
foldr' = reflect (Proxy @(FoldrSym2 @_ @_ @[] cons nil))

16  foldr' = reflect (Proxy @(FoldrSym2 @_ @_ @[] cons nil))
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
This confuses me, for some reason GHC doesn't see that the context is equal to the required `Reifies` constraint, or perhaps there is some hidden information that prevents GHC from resolving that constraint.
This is with GHC 8.10.49.4.1https://gitlab.haskell.org/ghc/ghc//issues/19929Using equality constraint in datatype kind signature leads to various strange...20210614T04:47:03ZJakob BrünkerUsing equality constraint in datatype kind signature leads to various strange behaviorsThe following file
```haskell
{# LANGUAGE DataKinds , TypeFamilies #}
module Weird where
import Data.Kind
type Weird :: forall a > (a ~ Char) => Type
data Weird a = MkWeird a
deriving Show
```
allows this GHCi session:
```haskell
ghci> :t MkWeird
 This looks like a kind error, and is impossible to write
MkWeird :: forall a {ev :: a ~ Char}. a > Weird a
ghci> MkWeird "foo"
 this is fine  but shouldn't be! The argument to MkWeird must be a Char, not String
MkWeird "foo"
ghci> :t MkWeird "foo"
 We can ask for the type
MkWeird "foo" :: Weird String
ghci> :t MkWeird "foo" :: Weird String
 but checking that same type results in a kind error
 (shouldn't this be a type error instead?)
<interactive>:1:18: error:
* Couldn't match kind `[Char]' with `Char'
[...]
ghci> import Data.Dynamic
ghci> Data.Dynamic.toDyn (MkWeird 'c' :: Weird Char)
 what is <>?
<interactive>:50:1: error:
* No instance for (Typeable <>) arising from a use of `toDyn'
[...]
ghci> :i Show
 The derived Show instance would be impossible to write manually
[...]
instance forall a (ev :: a ~ Char). Show a => Show (Weird a)
[...]
```
## Environment
* GHC version used: 9.3.20210529
Optional:
* Operating System: Arch on WSL2 on Windows 10
* System Architecture: x86_64The following file
```haskell
{# LANGUAGE DataKinds , TypeFamilies #}
module Weird where
import Data.Kind
type Weird :: forall a > (a ~ Char) => Type
data Weird a = MkWeird a
deriving Show
```
allows this GHCi session:
```haskell
ghci> :t MkWeird
 This looks like a kind error, and is impossible to write
MkWeird :: forall a {ev :: a ~ Char}. a > Weird a
ghci> MkWeird "foo"
 this is fine  but shouldn't be! The argument to MkWeird must be a Char, not String
MkWeird "foo"
ghci> :t MkWeird "foo"
 We can ask for the type
MkWeird "foo" :: Weird String
ghci> :t MkWeird "foo" :: Weird String
 but checking that same type results in a kind error
 (shouldn't this be a type error instead?)
<interactive>:1:18: error:
* Couldn't match kind `[Char]' with `Char'
[...]
ghci> import Data.Dynamic
ghci> Data.Dynamic.toDyn (MkWeird 'c' :: Weird Char)
 what is <>?
<interactive>:50:1: error:
* No instance for (Typeable <>) arising from a use of `toDyn'
[...]
ghci> :i Show
 The derived Show instance would be impossible to write manually
[...]
instance forall a (ev :: a ~ Char). Show a => Show (Weird a)
[...]
```
## Environment
* GHC version used: 9.3.20210529
Optional:
* Operating System: Arch on WSL2 on Windows 10
* System Architecture: x86_64https://gitlab.haskell.org/ghc/ghc//issues/19974Nonterminating substitution with derived constraints20210630T13:36:28ZsheafNonterminating substitution with derived constraints@rae reports the following issue, introduced by the removal of flattening variables (8bb52d91).
```haskell
{# LANGUAGE TypeFamilies, FunctionalDependencies, FlexibleInstances,
FlexibleContexts, ScopedTypeVariables #}
module Bug where
type family F a
class C a b  a > b where
meth :: a > b > ()
g :: forall a b. (F b ~ F a) => a > b > ()
g x y = const () (meth True x, meth False y, [undefined :: F a, True])
```
```
* Reduction stack overflow; size = 201
When simplifying the following type: F a
Use freductiondepth=0 to disable this check
(any upper bound you could choose might fail unpredictably with
minor updates to GHC, so disabling the check is recommended if
you're sure that type checking should terminate)
* In the expression: undefined :: F a
In the expression: [undefined :: F a, True]
In the second argument of `const', namely
`(meth True x, meth False y, [undefined :: F a, True])'

11  g x y = const () (meth True x, meth False y, [undefined :: F a, True])
 ^^^^^^^^^^^^^^^^
```
The problem is that we end up with inerts:
```
[G] co {0} :: F b[sk:1] ~# F a[sk:1] (CEqCan)
[D] _ {0}:: a[sk:1] ~# b[sk:1] (CEqCan)
```
and work item
```
[D] _ {0}:: F a[sk:1] ~# Bool (CEqCan)
```
This causes a loop as the substitution associated to the inert set is not terminating, rewriting `F a` to `F b` (using the Derived) then back to `F a` (using the Given).

Note that a similar situation can happen if we allow Wanteds to rewrite Wanteds (see test case `T3440`):
```haskell
type family Fam a :: Type
data GADT :: Type > Type where
GADT :: a > Fam a > GADT (Fam a)
unwrap :: GADT (Fam a) > (a, Fam a)
unwrap (GADT x y) = (x, y)
```
In that case we end up with inert set
```
[G] F b[sk:1] ~# F a[sk:1] (CEqCan)
[W] a[sk:1] ~# b[sk:1] (CEqCan)
```
which causes the same loop when trying to rewrite another wanted involving `a` or `b`.@rae reports the following issue, introduced by the removal of flattening variables (8bb52d91).
```haskell
{# LANGUAGE TypeFamilies, FunctionalDependencies, FlexibleInstances,
FlexibleContexts, ScopedTypeVariables #}
module Bug where
type family F a
class C a b  a > b where
meth :: a > b > ()
g :: forall a b. (F b ~ F a) => a > b > ()
g x y = const () (meth True x, meth False y, [undefined :: F a, True])
```
```
* Reduction stack overflow; size = 201
When simplifying the following type: F a
Use freductiondepth=0 to disable this check
(any upper bound you could choose might fail unpredictably with
minor updates to GHC, so disabling the check is recommended if
you're sure that type checking should terminate)
* In the expression: undefined :: F a
In the expression: [undefined :: F a, True]
In the second argument of `const', namely
`(meth True x, meth False y, [undefined :: F a, True])'

11  g x y = const () (meth True x, meth False y, [undefined :: F a, True])
 ^^^^^^^^^^^^^^^^
```
The problem is that we end up with inerts:
```
[G] co {0} :: F b[sk:1] ~# F a[sk:1] (CEqCan)
[D] _ {0}:: a[sk:1] ~# b[sk:1] (CEqCan)
```
and work item
```
[D] _ {0}:: F a[sk:1] ~# Bool (CEqCan)
```
This causes a loop as the substitution associated to the inert set is not terminating, rewriting `F a` to `F b` (using the Derived) then back to `F a` (using the Given).

Note that a similar situation can happen if we allow Wanteds to rewrite Wanteds (see test case `T3440`):
```haskell
type family Fam a :: Type
data GADT :: Type > Type where
GADT :: a > Fam a > GADT (Fam a)
unwrap :: GADT (Fam a) > (a, Fam a)
unwrap (GADT x y) = (x, y)
```
In that case we end up with inert set
```
[G] F b[sk:1] ~# F a[sk:1] (CEqCan)
[W] a[sk:1] ~# b[sk:1] (CEqCan)
```
which causes the same loop when trying to rewrite another wanted involving `a` or `b`.https://gitlab.haskell.org/ghc/ghc//issues/20000Use predicates in the constraint solver20210617T09:58:30ZKrzysztof GogolewskiUse predicates in the constraint solverSometimes it would be useful if type inference could emit a requirement that does not have a corresponding constraint in Haskell.
For example, when typechecking the body of a forall, we should require that its kind is either `TYPE r` or `Constraint`. This could be done with a predicate `TypeLike a`. The evidence for a TypeLike is a coercion whose righthand side is either `TYPE r` or `Constraint`.
Implementation plan: make it so that constraints (`Ct`s and friends) are no longer classified by types, but are classified directly by PredTrees. (Rename that type, too.) Then, make TypeLike a constructor in PredTree. This means we don't have to wire in a type that will be used only internally. Create a coercion hole when the TypeLike constraint arises.
TypeLike is used only in the typechecker and is absent in Core. However, most predicates can have a corresponding Core Lint check.
This ticket will be useful in:
* #15979 #19573 #8388 TypeLike: body of a forall, either TYPE r or Constraint
* Likewise tuple inference: either Type or Constraint
* #17201 FixedRuntimeRep, also should fix #13105 #17518 #17536 #18170
* #17368 Homogeneous equality
* #18756 Linear types submultiplicity
* #19915 Perhaps tagToEnum/withDict
WIP branch: !2857Sometimes it would be useful if type inference could emit a requirement that does not have a corresponding constraint in Haskell.
For example, when typechecking the body of a forall, we should require that its kind is either `TYPE r` or `Constraint`. This could be done with a predicate `TypeLike a`. The evidence for a TypeLike is a coercion whose righthand side is either `TYPE r` or `Constraint`.
Implementation plan: make it so that constraints (`Ct`s and friends) are no longer classified by types, but are classified directly by PredTrees. (Rename that type, too.) Then, make TypeLike a constructor in PredTree. This means we don't have to wire in a type that will be used only internally. Create a coercion hole when the TypeLike constraint arises.
TypeLike is used only in the typechecker and is absent in Core. However, most predicates can have a corresponding Core Lint check.
This ticket will be useful in:
* #15979 #19573 #8388 TypeLike: body of a forall, either TYPE r or Constraint
* Likewise tuple inference: either Type or Constraint
* #17201 FixedRuntimeRep, also should fix #13105 #17518 #17536 #18170
* #17368 Homogeneous equality
* #18756 Linear types submultiplicity
* #19915 Perhaps tagToEnum/withDict
WIP branch: !2857https://gitlab.haskell.org/ghc/ghc//issues/20009Degradation in error message clarity for ` GHC.TypeNats.<=?`20210624T17:43:47ZChristiaan BaaijDegradation in error message clarity for ` GHC.TypeNats.<=?`## Summary
With the introduction of https://gitlab.haskell.org/ghc/ghc//commit/eea96042f1e8682605ae68db10f2bcdd7dab923e the clarity of error messages involving `GHC.TypeNats.<=?` has degraded compared to GHC 9.0.1 or earlier.
## Steps to reproduce
Given this code `TestInEq.hs`:
```haskell
{# LANGUAGE DataKinds, TypeFamilies, TypeOperators #}
module TestInEq where
import Data.Proxy
import GHC.TypeLits
proxyInEq :: (a <= b) => Proxy a > Proxy b > ()
proxyInEq _ _ = ()
proxyInEq1 :: Proxy a > Proxy (a+1) > ()
proxyInEq1 = proxyInEq
```
## Expected behavior
On GHC 9.0.1 and prior, one would get the error message:
```
$ ghci TestInEq.hs
GHCi, version 9.0.1: https://www.haskell.org/ghc/ :? for help
[1 of 1] Compiling TestInEq ( TestInEq.hs, interpreted )
TestInEq.hs:11:14: error:
• Couldn't match type ‘a <=? (a + 1)’ with ‘'True’
arising from a use of ‘proxyInEq’
• In the expression: proxyInEq
In an equation for ‘proxyInEq1’: proxyInEq1 = proxyInEq
• Relevant bindings include
proxyInEq1 :: Proxy a > Proxy (a + 1) > ()
(bound at TestInEq.hs:11:1)

11  proxyInEq1 = proxyInEq
 ^^^^^^^^^
Failed, no modules loaded.
ghci>
```
But on GHC 9.2.0.20210422, which includes https://gitlab.haskell.org/ghc/ghc//commit/eea96042f1e8682605ae68db10f2bcdd7dab923e, one gets the following error message
```
$ ghci TestInEq.hs
GHCi, version 9.2.0.20210422: https://www.haskell.org/ghc/ :? for help
[1 of 1] Compiling TestInEq ( TestInEq.hs, interpreted )
TestInEq.hs:11:14: error:
• Couldn't match type ‘Data.Type.Ord.OrdCond
(CmpNat a (a + 1)) 'True 'True 'False’
with ‘'True’
arising from a use of ‘proxyInEq’
• In the expression: proxyInEq
In an equation for ‘proxyInEq1’: proxyInEq1 = proxyInEq
• Relevant bindings include
proxyInEq1 :: Proxy a > Proxy (a + 1) > ()
(bound at TestInEq.hs:11:1)

11  proxyInEq1 = proxyInEq
 ^^^^^^^^^
Failed, no modules loaded.
ghci>
```
which I feel is far less clear.
At the least, I hope we can recover the error message of GHC 9.0.1 or earlier. And it would be even nicer if this could be fixed before the GHC 9.2.1 release. I can envision at least three possible solutions:
1. Reinstate `(GHC.TypeNats.<=?) :: Nat > Nat > Bool` as a builtin type family
2. Somehow add a custom typeerror to `Data.Type.Ord.OrdCond`
3. Don't expand type aliases in type errors
Following up on 3, it would be even nicer if we could actually get an error along the lines of:
```
TestInEq.hs:11:14: error:
• Couldn't satisfy ‘a <= (a + 1)’
arising from a use of ‘proxyInEq’
• In the expression: proxyInEq
In an equation for ‘proxyInEq1’: proxyInEq1 = proxyInEq
• Relevant bindings include
proxyInEq1 :: Proxy a > Proxy (a + 1) > ()
(bound at TestInEq.hs:11:1)

11  proxyInEq1 = proxyInEq
 ^^^^^^^^^
```
where the type synonym `(GHC.TypeNats.<=) :: Nat > Nat > Constraint` isn't expanded either.
This issue was/is also discussed at: https://mail.haskell.org/pipermail/ghcdevs/2021June/019992.html
## Environment
* GHC version used: 9.2.0.20210422## Summary
With the introduction of https://gitlab.haskell.org/ghc/ghc//commit/eea96042f1e8682605ae68db10f2bcdd7dab923e the clarity of error messages involving `GHC.TypeNats.<=?` has degraded compared to GHC 9.0.1 or earlier.
## Steps to reproduce
Given this code `TestInEq.hs`:
```haskell
{# LANGUAGE DataKinds, TypeFamilies, TypeOperators #}
module TestInEq where
import Data.Proxy
import GHC.TypeLits
proxyInEq :: (a <= b) => Proxy a > Proxy b > ()
proxyInEq _ _ = ()
proxyInEq1 :: Proxy a > Proxy (a+1) > ()
proxyInEq1 = proxyInEq
```
## Expected behavior
On GHC 9.0.1 and prior, one would get the error message:
```
$ ghci TestInEq.hs
GHCi, version 9.0.1: https://www.haskell.org/ghc/ :? for help
[1 of 1] Compiling TestInEq ( TestInEq.hs, interpreted )
TestInEq.hs:11:14: error:
• Couldn't match type ‘a <=? (a + 1)’ with ‘'True’
arising from a use of ‘proxyInEq’
• In the expression: proxyInEq
In an equation for ‘proxyInEq1’: proxyInEq1 = proxyInEq
• Relevant bindings include
proxyInEq1 :: Proxy a > Proxy (a + 1) > ()
(bound at TestInEq.hs:11:1)

11  proxyInEq1 = proxyInEq
 ^^^^^^^^^
Failed, no modules loaded.
ghci>
```
But on GHC 9.2.0.20210422, which includes https://gitlab.haskell.org/ghc/ghc//commit/eea96042f1e8682605ae68db10f2bcdd7dab923e, one gets the following error message
```
$ ghci TestInEq.hs
GHCi, version 9.2.0.20210422: https://www.haskell.org/ghc/ :? for help
[1 of 1] Compiling TestInEq ( TestInEq.hs, interpreted )
TestInEq.hs:11:14: error:
• Couldn't match type ‘Data.Type.Ord.OrdCond
(CmpNat a (a + 1)) 'True 'True 'False’
with ‘'True’
arising from a use of ‘proxyInEq’
• In the expression: proxyInEq
In an equation for ‘proxyInEq1’: proxyInEq1 = proxyInEq
• Relevant bindings include
proxyInEq1 :: Proxy a > Proxy (a + 1) > ()
(bound at TestInEq.hs:11:1)

11  proxyInEq1 = proxyInEq
 ^^^^^^^^^
Failed, no modules loaded.
ghci>
```
which I feel is far less clear.
At the least, I hope we can recover the error message of GHC 9.0.1 or earlier. And it would be even nicer if this could be fixed before the GHC 9.2.1 release. I can envision at least three possible solutions:
1. Reinstate `(GHC.TypeNats.<=?) :: Nat > Nat > Bool` as a builtin type family
2. Somehow add a custom typeerror to `Data.Type.Ord.OrdCond`
3. Don't expand type aliases in type errors
Following up on 3, it would be even nicer if we could actually get an error along the lines of:
```
TestInEq.hs:11:14: error:
• Couldn't satisfy ‘a <= (a + 1)’
arising from a use of ‘proxyInEq’
• In the expression: proxyInEq
In an equation for ‘proxyInEq1’: proxyInEq1 = proxyInEq
• Relevant bindings include
proxyInEq1 :: Proxy a > Proxy (a + 1) > ()
(bound at TestInEq.hs:11:1)

11  proxyInEq1 = proxyInEq
 ^^^^^^^^^
```
where the type synonym `(GHC.TypeNats.<=) :: Nat > Nat > Constraint` isn't expanded either.
This issue was/is also discussed at: https://mail.haskell.org/pipermail/ghcdevs/2021June/019992.html
## Environment
* GHC version used: 9.2.0.20210422https://gitlab.haskell.org/ghc/ghc//issues/20048Difference between (Coercible f g) and (forall x. Coercible (f x) (g x))20210628T01:08:56ZOleg GrenrusDifference between (Coercible f g) and (forall x. Coercible (f x) (g x))```haskell
{# LANGUAGE QuantifiedConstraints, RankNTypes #}
{# LANGUAGE AllowAmbiguousTypes, TypeApplications #}
import Data.Coerce
import Data.Functor.Identity
import Data.Functor.Compose
coeA :: Coercible f g => f x > g x
coeA = coerce
 This doesn't work:
 • Couldn't match representation of type ‘Identity’
 with that of ‘Compose Identity Identity’
 arising from a use of ‘coeA’

 exA :: Identity a > Compose Identity Identity a
 exA = coeA
 This works however.
exB :: Identity a > Compose Identity Identity a
exB = coerce
 and also
coeC :: (forall x. Coercible (f x) (g x)) => f x > g x
coeC = coerce
exC :: Identity a > Compose Identity Identity a
exC = coeC
 So this works:
forward :: Coercible f g => ((forall x. Coercible (f x) (g x)) => r) > r
forward k = k
 but this doesn't?
 backwards :: (forall x. Coercible (f x) (g x)) => (Coercible f g => r) > r
 backwards k = k
 but what is the difference between

 Coercible f g

 and

 (forall x. Coercible (f x) (g x))

 As far as I can tell from reading zerocost coercions paper,
 Co_App rule:

 Γ ⊢ γ₁ : τ₁ ~ρ σ₁
 Γ ⊢ γ₂ : τ₂ ∼N σ₂
 Γ ⊢ τ₁ τ₂ : κ
 Γ ⊢ σ₁ σ₂ : κ
 
 Γ ⊢ γ₁ γ₂ : τ₁ τ₂ ~ρ σ₁ σ₂

 Is used to show the forward direction,
 but why the backwards, functionalextensionality like, direction is not included?
 What will break?

 It feels that there could be some kind of Co_Abs rule, essentially doing the opposite of Co_App.
```
EDIT: This obviously affects `~` equality too. I don't see why `f ~ g` and `forall x. f x ~ g x` would not be equivalent in GHC type system.```haskell
{# LANGUAGE QuantifiedConstraints, RankNTypes #}
{# LANGUAGE AllowAmbiguousTypes, TypeApplications #}
import Data.Coerce
import Data.Functor.Identity
import Data.Functor.Compose
coeA :: Coercible f g => f x > g x
coeA = coerce
 This doesn't work:
 • Couldn't match representation of type ‘Identity’
 with that of ‘Compose Identity Identity’
 arising from a use of ‘coeA’

 exA :: Identity a > Compose Identity Identity a
 exA = coeA
 This works however.
exB :: Identity a > Compose Identity Identity a
exB = coerce
 and also
coeC :: (forall x. Coercible (f x) (g x)) => f x > g x
coeC = coerce
exC :: Identity a > Compose Identity Identity a
exC = coeC
 So this works:
forward :: Coercible f g => ((forall x. Coercible (f x) (g x)) => r) > r
forward k = k
 but this doesn't?
 backwards :: (forall x. Coercible (f x) (g x)) => (Coercible f g => r) > r
 backwards k = k
 but what is the difference between

 Coercible f g

 and

 (forall x. Coercible (f x) (g x))

 As far as I can tell from reading zerocost coercions paper,
 Co_App rule:

 Γ ⊢ γ₁ : τ₁ ~ρ σ₁
 Γ ⊢ γ₂ : τ₂ ∼N σ₂
 Γ ⊢ τ₁ τ₂ : κ
 Γ ⊢ σ₁ σ₂ : κ
 
 Γ ⊢ γ₁ γ₂ : τ₁ τ₂ ~ρ σ₁ σ₂

 Is used to show the forward direction,
 but why the backwards, functionalextensionality like, direction is not included?
 What will break?

 It feels that there could be some kind of Co_Abs rule, essentially doing the opposite of Co_App.
```
EDIT: This obviously affects `~` equality too. I don't see why `f ~ g` and `forall x. f x ~ g x` would not be equivalent in GHC type system.https://gitlab.haskell.org/ghc/ghc//issues/20063No skolem info panic involving typed hole20210630T10:40:36ZsheafNo skolem info panic involving typed holeThe following program causes a `No skolem info` panic on GHC 9.0.1, 9.2.1, HEAD, but not on GHC 8.10.5.
```haskell
{# LANGUAGE DataKinds #}
{# LANGUAGE GADTs #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE RankNTypes #}
{# LANGUAGE StandaloneKindSignatures #}
{# LANGUAGE TypeApplications #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE TypeOperators #}
module Bug where
data Context where
Extend :: forall k. Context > Context
type (:*&) :: Context > forall k > Context
type ctx :*& k = Extend @k ctx
data Idx ctx where
T :: Idx ctx > Idx (ctx :*& l)
data Rn ctx1 ctx2 where
U :: Rn ctx1 ctx2 > Rn (ctx1 :*& l) (ctx2 :*& l)
rnRename :: Rn ctx1 ctx2 > Idx ctx3 > Idx ctx4
rnRename (U _ ) _ = T _
rnRename _ T = undefined
```
```
[1 of 1] Compiling Bug ( src\Bug.hs, interpreted )
ghc.exe: panic! (the 'impossible' happened)
(GHC version 9.0.1:
No skolem info:
[ctx4_aBB[sk:1]]
```
The program should be rejected, and the error given with GHC 8.10.5 seems perfect:
```
[1 of 1] Compiling Bug ( src\Bug.hs, interpreted )
src\Bug.hs:26:17: error:
• The constructor ‘T’ should have 1 argument, but has been given none
• In the pattern: T
In an equation for ‘rnRename’: rnRename _ T = undefined

26  rnRename _ T = undefined
 ^
```
The issue seems to be related to the presence of a typed hole on the line prior to the bogus pattern match.The following program causes a `No skolem info` panic on GHC 9.0.1, 9.2.1, HEAD, but not on GHC 8.10.5.
```haskell
{# LANGUAGE DataKinds #}
{# LANGUAGE GADTs #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE RankNTypes #}
{# LANGUAGE StandaloneKindSignatures #}
{# LANGUAGE TypeApplications #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE TypeOperators #}
module Bug where
data Context where
Extend :: forall k. Context > Context
type (:*&) :: Context > forall k > Context
type ctx :*& k = Extend @k ctx
data Idx ctx where
T :: Idx ctx > Idx (ctx :*& l)
data Rn ctx1 ctx2 where
U :: Rn ctx1 ctx2 > Rn (ctx1 :*& l) (ctx2 :*& l)
rnRename :: Rn ctx1 ctx2 > Idx ctx3 > Idx ctx4
rnRename (U _ ) _ = T _
rnRename _ T = undefined
```
```
[1 of 1] Compiling Bug ( src\Bug.hs, interpreted )
ghc.exe: panic! (the 'impossible' happened)
(GHC version 9.0.1:
No skolem info:
[ctx4_aBB[sk:1]]
```
The program should be rejected, and the error given with GHC 8.10.5 seems perfect:
```
[1 of 1] Compiling Bug ( src\Bug.hs, interpreted )
src\Bug.hs:26:17: error:
• The constructor ‘T’ should have 1 argument, but has been given none
• In the pattern: T
In an equation for ‘rnRename’: rnRename _ T = undefined

26  rnRename _ T = undefined
 ^
```
The issue seems to be related to the presence of a typed hole on the line prior to the bogus pattern match.https://gitlab.haskell.org/ghc/ghc//issues/20064When does GHC quantify over variables fully determined by fundeps?20210630T13:36:28ZsheafWhen does GHC quantify over variables fully determined by fundeps?Consider the following example:
```haskell
{# LANGUAGE FlexibleContexts, FunctionalDependencies, NoMonomorphismRestriction #}
data AB a b = AB
class C a b  a > b where
meth :: AB a b > b
ab :: AB Int b
ab = AB
foo :: C Int b => b
foo = meth ab
```
GHC is able to infer the commented type for `foo`. Some other test cases which present the same behaviour are `tc231` where we have
```haskell
data Z a = ...
data Q s a chain = ...
class Zork s a b  a > b where ...
```
where GHC will infer the following type for `foo`:
```
foo :: Zork s (Z [Char]) b => Q s (Z [Char]) chain > ST s ()
foo = ...
```
and `tcfail093`, where we have
```haskell
class Call c h  c > h where ...
```
and GHC will infer the following type for `dup`:
```haskell
dup :: Call (IO Int) h => () > Int > h
dup = ...
```
@rae's patch to remove Deriveds changes all these programs to throw type errors. So for the first one we get:
```
* No instance for (C Int b0) arising from a use of `meth'
* In the expression: meth ab
In an equation for `foo': foo = meth ab

12  foo = meth ab
 ^^^^^^^
```
for `tc231` we get:
```
* No instance for (Zork s (Z [Char]) b0)
arising from a use of `huh'
* In the expression: huh (s b)
In an equation for `foo': foo b = huh (s b)
```
and for `tcfail093` we get:
```
* No instance for (Call (IO Int) h0) arising from a use of `call'
* In the expression: call primDup
In an equation for `dup': dup () = call primDup
```
Pinging @simonpj for thoughts, as Simon committed a change that allowed `tc231` and `tcfail093` to both typecheck, justified by the (now removed) [Note [Important subtlety in oclose]](https://gitlab.haskell.org/ghc/ghc//commit/ecddaca17dccbe1d0b56220d838fce8bc4b97884#ef94ac21ad807a07e51886b7e2a0abf22cd9772f_82_79). That note remarks that cases such as `tcfail093` are "right on the borderline", so it seems reasonable to revert back to throwing an error.Consider the following example:
```haskell
{# LANGUAGE FlexibleContexts, FunctionalDependencies, NoMonomorphismRestriction #}
data AB a b = AB
class C a b  a > b where
meth :: AB a b > b
ab :: AB Int b
ab = AB
foo :: C Int b => b
foo = meth ab
```
GHC is able to infer the commented type for `foo`. Some other test cases which present the same behaviour are `tc231` where we have
```haskell
data Z a = ...
data Q s a chain = ...
class Zork s a b  a > b where ...
```
where GHC will infer the following type for `foo`:
```
foo :: Zork s (Z [Char]) b => Q s (Z [Char]) chain > ST s ()
foo = ...
```
and `tcfail093`, where we have
```haskell
class Call c h  c > h where ...
```
and GHC will infer the following type for `dup`:
```haskell
dup :: Call (IO Int) h => () > Int > h
dup = ...
```
@rae's patch to remove Deriveds changes all these programs to throw type errors. So for the first one we get:
```
* No instance for (C Int b0) arising from a use of `meth'
* In the expression: meth ab
In an equation for `foo': foo = meth ab

12  foo = meth ab
 ^^^^^^^
```
for `tc231` we get:
```
* No instance for (Zork s (Z [Char]) b0)
arising from a use of `huh'
* In the expression: huh (s b)
In an equation for `foo': foo b = huh (s b)
```
and for `tcfail093` we get:
```
* No instance for (Call (IO Int) h0) arising from a use of `call'
* In the expression: call primDup
In an equation for `dup': dup () = call primDup
```
Pinging @simonpj for thoughts, as Simon committed a change that allowed `tc231` and `tcfail093` to both typecheck, justified by the (now removed) [Note [Important subtlety in oclose]](https://gitlab.haskell.org/ghc/ghc//commit/ecddaca17dccbe1d0b56220d838fce8bc4b97884#ef94ac21ad807a07e51886b7e2a0abf22cd9772f_82_79). That note remarks that cases such as `tcfail093` are "right on the borderline", so it seems reasonable to revert back to throwing an error.https://gitlab.haskell.org/ghc/ghc//issues/20133Representationpolymorphic backpack drops a type argument in a variant of T1395520210719T23:56:23ZsheafRepresentationpolymorphic backpack drops a type argument in a variant of T13955GHC seems to get confused with the following `.bkp` backpack file modified from test case `T13955` in which an argument is added to the `Rep` declaration:
```haskell
{# LANGUAGE MagicHash #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE DataKinds #}
unit numberunknown where
signature NumberUnknown where
import GHC.Types
data Rep a :: RuntimeRep
data Number a :: TYPE (Rep a)
plus :: Number a > Number a > Number a
multiply :: Number a > Number a > Number a
module NumberStuff where
import NumberUnknown
funcA :: Number a > Number a > Number a
funcA x y = plus x (multiply x y)
unit numberunboxedint where
module NumberUnknown where
import GHC.Types
import GHC.Prim
type Rep a = IntRep
type Number a = Int#
plus :: Int# > Int# > Int#
plus = (+#)
multiply :: Int# > Int# > Int#
multiply = (*#)
unit main where
dependency numberunknown[NumberUnknown=numberunboxedint:NumberUnknown]
module Main where
import NumberStuff
import GHC.Types
main = print (I# (funcA 2# 3#))
```
Compiled with `ghc T13955b.bkp backpack`, we get the error:
```
T13955b.bkp:15:14: error:
* Expected kind `k0 > *',
but `Number' has kind `TYPE 'GHC.Types.IntRep'
* In the type signature: funcA :: Number a > Number a > Number a

15  funcA :: Number a > Number a > Number a
 ^^^^^^^^
T13955b.bkp:15:26: error:
* Expected kind `k0 > *',
but `Number' has kind `TYPE 'GHC.Types.IntRep'
* In the type signature: funcA :: Number a > Number a > Number a

15  funcA :: Number a > Number a > Number a
 ^^^^^^^^
T13955b.bkp:15:38: error:
* Expected kind `k0 > *',
but `Number' has kind `TYPE 'GHC.Types.IntRep'
* In the type signature: funcA :: Number a > Number a > Number a

15  funcA :: Number a > Number a > Number a
 ^^^^^^^^
```
It looks like GHC gets confused when typechecking `main` (indeed, commenting it out prevents the error); so the line numbers should be understood as referring to the instantiation of the `NumberUnknown` signature.
This is what `ddumptctrace` looks like starting from there:
```
[3 of 3] Processing main
Instantiating main
[1 of 1] Including numberunknown[NumberUnknown=numberunboxedint:NumberUnknown]
Instantiating numberunknown[NumberUnknown=numberunboxedint:NumberUnknown]
[1 of 2] Compiling NumberUnknown[sig] ( numberunknown\NumberUnknown.hsig, nothing ) [Source file changed]
checkHsigIface
[ryc :> Identifier `multiply', ryd :> Identifier `plus',
rye :> Type constructor `Number', ryf :> Type constructor `Rep',
ryg :> Identifier `numberunboxedint:NumberUnknown.$trModule',
ryU :> Identifier `numberunboxedint:NumberUnknown.$tcNumber',
ryV :> Identifier `numberunboxedint:NumberUnknown.$tcRep']
[]
[multiply, plus, Number{Number}, Rep{Rep}]
[2 of 2] Compiling NumberStuff ( numberunknown\NumberStuff.hs, nothing ) [Source file changed]
Adding diagnostic:
testsuite\tests\backpack\should_run\T13955b.bkp:13:3:
Module `Prelude' implicitly imported
checkFamInstConsistency [Prelude, NumberUnknown]
Tc2 (src)
Tc3
tcExtendKindEnvList []
tcExtendKindEnvList []
tcDeriving []
rnd
Adding instances:
Tc3b
Tc3c
tcSemigroupWarnings
Tc4
Tc4a
Tc5
tcExtendKindEnvList []
tcHsSigType { Number a_ayY > Number a_ayY > Number a_ayY
pushLevelAndSolveEqualitiesX { Called from tc_lhs_sig_type
newAnonMetaTyVar t_az1[tau:1]
pushLevelAndCaptureConstraints { 2
newMetaKindVar k_az2[tau:2]
bindImplicitTKBndrsX
[a_ayY]
[a_ayY[sk:2]]
tc_extend_local_env
[(a_ayY, Type variable `a_ayY' = a_ayY[sk:2] :: k_az2[tau:2])]
tcExtendBinderStack [a_ayY a_ayY[sk:2]]
newAnonMetaTyVar t_az3[tau:2]
newAnonMetaTyVar t_az4[tau:2]
lk1 Number
tcInferTyApps {
Number
[HsValArg a_ayY]
newMetaKindVar k_az5[tau:2]
newMetaKindVar k_az6[tau:2]
u_tys
tclvl 2
TYPE 'GHC.Types.IntRep ~ k_az5[tau:2] > k_az6[tau:2]
a type equality[True] TYPE 'GHC.Types.IntRep
~
k_az5[tau:2] > k_az6[tau:2]
```
We see here that GHC gets confused about the kind of `Number` (it thinks `Number :: TYPE IntRep`, somehow ignoring that `Number` takes an argument), and it all goes downhill from there.
Sorry for the ticket title, I didn't really know how to summarise the issue. I'm not very familiar with backpack, so I apologise if I made an elementary error somewhere.GHC seems to get confused with the following `.bkp` backpack file modified from test case `T13955` in which an argument is added to the `Rep` declaration:
```haskell
{# LANGUAGE MagicHash #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE DataKinds #}
unit numberunknown where
signature NumberUnknown where
import GHC.Types
data Rep a :: RuntimeRep
data Number a :: TYPE (Rep a)
plus :: Number a > Number a > Number a
multiply :: Number a > Number a > Number a
module NumberStuff where
import NumberUnknown
funcA :: Number a > Number a > Number a
funcA x y = plus x (multiply x y)
unit numberunboxedint where
module NumberUnknown where
import GHC.Types
import GHC.Prim
type Rep a = IntRep
type Number a = Int#
plus :: Int# > Int# > Int#
plus = (+#)
multiply :: Int# > Int# > Int#
multiply = (*#)
unit main where
dependency numberunknown[NumberUnknown=numberunboxedint:NumberUnknown]
module Main where
import NumberStuff
import GHC.Types
main = print (I# (funcA 2# 3#))
```
Compiled with `ghc T13955b.bkp backpack`, we get the error:
```
T13955b.bkp:15:14: error:
* Expected kind `k0 > *',
but `Number' has kind `TYPE 'GHC.Types.IntRep'
* In the type signature: funcA :: Number a > Number a > Number a

15  funcA :: Number a > Number a > Number a
 ^^^^^^^^
T13955b.bkp:15:26: error:
* Expected kind `k0 > *',
but `Number' has kind `TYPE 'GHC.Types.IntRep'
* In the type signature: funcA :: Number a > Number a > Number a

15  funcA :: Number a > Number a > Number a
 ^^^^^^^^
T13955b.bkp:15:38: error:
* Expected kind `k0 > *',
but `Number' has kind `TYPE 'GHC.Types.IntRep'
* In the type signature: funcA :: Number a > Number a > Number a

15  funcA :: Number a > Number a > Number a
 ^^^^^^^^
```
It looks like GHC gets confused when typechecking `main` (indeed, commenting it out prevents the error); so the line numbers should be understood as referring to the instantiation of the `NumberUnknown` signature.
This is what `ddumptctrace` looks like starting from there:
```
[3 of 3] Processing main
Instantiating main
[1 of 1] Including numberunknown[NumberUnknown=numberunboxedint:NumberUnknown]
Instantiating numberunknown[NumberUnknown=numberunboxedint:NumberUnknown]
[1 of 2] Compiling NumberUnknown[sig] ( numberunknown\NumberUnknown.hsig, nothing ) [Source file changed]
checkHsigIface
[ryc :> Identifier `multiply', ryd :> Identifier `plus',
rye :> Type constructor `Number', ryf :> Type constructor `Rep',
ryg :> Identifier `numberunboxedint:NumberUnknown.$trModule',
ryU :> Identifier `numberunboxedint:NumberUnknown.$tcNumber',
ryV :> Identifier `numberunboxedint:NumberUnknown.$tcRep']
[]
[multiply, plus, Number{Number}, Rep{Rep}]
[2 of 2] Compiling NumberStuff ( numberunknown\NumberStuff.hs, nothing ) [Source file changed]
Adding diagnostic:
testsuite\tests\backpack\should_run\T13955b.bkp:13:3:
Module `Prelude' implicitly imported
checkFamInstConsistency [Prelude, NumberUnknown]
Tc2 (src)
Tc3
tcExtendKindEnvList []
tcExtendKindEnvList []
tcDeriving []
rnd
Adding instances:
Tc3b
Tc3c
tcSemigroupWarnings
Tc4
Tc4a
Tc5
tcExtendKindEnvList []
tcHsSigType { Number a_ayY > Number a_ayY > Number a_ayY
pushLevelAndSolveEqualitiesX { Called from tc_lhs_sig_type
newAnonMetaTyVar t_az1[tau:1]
pushLevelAndCaptureConstraints { 2
newMetaKindVar k_az2[tau:2]
bindImplicitTKBndrsX
[a_ayY]
[a_ayY[sk:2]]
tc_extend_local_env
[(a_ayY, Type variable `a_ayY' = a_ayY[sk:2] :: k_az2[tau:2])]
tcExtendBinderStack [a_ayY a_ayY[sk:2]]
newAnonMetaTyVar t_az3[tau:2]
newAnonMetaTyVar t_az4[tau:2]
lk1 Number
tcInferTyApps {
Number
[HsValArg a_ayY]
newMetaKindVar k_az5[tau:2]
newMetaKindVar k_az6[tau:2]
u_tys
tclvl 2
TYPE 'GHC.Types.IntRep ~ k_az5[tau:2] > k_az6[tau:2]
a type equality[True] TYPE 'GHC.Types.IntRep
~
k_az5[tau:2] > k_az6[tau:2]
```
We see here that GHC gets confused about the kind of `Number` (it thinks `Number :: TYPE IntRep`, somehow ignoring that `Number` takes an argument), and it all goes downhill from there.
Sorry for the ticket title, I didn't really know how to summarise the issue. I'm not very familiar with backpack, so I apologise if I made an elementary error somewhere.https://gitlab.haskell.org/ghc/ghc//issues/20146Unify wastes effort on casts20210727T21:31:47ZSimon Peyton JonesUnify wastes effort on castsIn GHC.Core.Unify the main `unify_ty` function has signature
```
unify_ty :: UMEnv
> Type > Type  Types to be unified and a co
> CoercionN  A coercion between their kinds
 See Note [Kind coercions in Unify]
> UM ()
```
That `CoercionN`, called `kco` in code, is derived from the idea in `eqType` that we
are comparing types *ignoring casts*.
The point of this ticket is **we do not know a single example where carrying kco makes unification succeed, where
it would otherwise fail**.
The simpler alternative is to have
```
unify_ty :: UMEnv
> Type > Type
> UM ()
```
and code like
```
unify_ty env (CastTy ty1' co1) (CastTy ty2 co2)
 isReflexiveCo (co1 `mkTransCo` sym co2)
= = unify_ty env ty1' ty2' (co1 `mkTransCo` kco `mkTransCo` mkSymCo co2)
unify_ty env (Cast {}) ty2 = surelyApart
unify_ty env ty1 (Cast {}) = surelyApart
```
You might think this would not work on something like
```
f :: t1 > t2
x :: t1
f x ~ ((f > co1) (x > co2)) > co3
where
co1 :: t1 > t2 ~ t3 > t4
co2 :: t1 ~ t3
co3 :: t4 ~ t2
```
But that's ruled out by invariant (EQ1) in `Note [Respecting definitional equality]` in GHC.Core.TyCo.Rep.
Similarly
```
(forall a. t1 > co) ~ (forall a. t2) > co2
```
is ruled out by (EQ4).In GHC.Core.Unify the main `unify_ty` function has signature
```
unify_ty :: UMEnv
> Type > Type  Types to be unified and a co
> CoercionN  A coercion between their kinds
 See Note [Kind coercions in Unify]
> UM ()
```
That `CoercionN`, called `kco` in code, is derived from the idea in `eqType` that we
are comparing types *ignoring casts*.
The point of this ticket is **we do not know a single example where carrying kco makes unification succeed, where
it would otherwise fail**.
The simpler alternative is to have
```
unify_ty :: UMEnv
> Type > Type
> UM ()
```
and code like
```
unify_ty env (CastTy ty1' co1) (CastTy ty2 co2)
 isReflexiveCo (co1 `mkTransCo` sym co2)
= = unify_ty env ty1' ty2' (co1 `mkTransCo` kco `mkTransCo` mkSymCo co2)
unify_ty env (Cast {}) ty2 = surelyApart
unify_ty env ty1 (Cast {}) = surelyApart
```
You might think this would not work on something like
```
f :: t1 > t2
x :: t1
f x ~ ((f > co1) (x > co2)) > co3
where
co1 :: t1 > t2 ~ t3 > t4
co2 :: t1 ~ t3
co3 :: t4 ~ t2
```
But that's ruled out by invariant (EQ1) in `Note [Respecting definitional equality]` in GHC.Core.TyCo.Rep.
Similarly
```
(forall a. t1 > co) ~ (forall a. t2) > co2
```
is ruled out by (EQ4).Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/20161Use a specific Reduction datatype instead of `(Type,Coercion)`20210725T21:43:41ZsheafUse a specific Reduction datatype instead of `(Type,Coercion)`As I discovered in !5909, introducing a datatype `data Reduction = Reduction Coercion !Type` for use in the rewriter, replacing pairs `(Type, Coercion)` has several benefits:
* improved performance in rewriting of type families (around 2.5% improvement in `T9872`),
* improved consistency around orientation of rewritings, as a `Reduction` is always lefttoright (the coercion's RHS type is always the type stored in the 'Reduction').
@rae suggested that this could be taken much further. His idea is to introduce combinators that work purely on the level of `Reduction`s, e.g. `mkReflRedn`, `mkTransRedn`, `mkTyConAppRedn`, etc. This means that other parts of the code won't have to worry about getting the orientations right (e.g. whether to use `mkCoherenceRightCo` or `mkCoherenceLeftCo`).As I discovered in !5909, introducing a datatype `data Reduction = Reduction Coercion !Type` for use in the rewriter, replacing pairs `(Type, Coercion)` has several benefits:
* improved performance in rewriting of type families (around 2.5% improvement in `T9872`),
* improved consistency around orientation of rewritings, as a `Reduction` is always lefttoright (the coercion's RHS type is always the type stored in the 'Reduction').
@rae suggested that this could be taken much further. His idea is to introduce combinators that work purely on the level of `Reduction`s, e.g. `mkReflRedn`, `mkTransRedn`, `mkTyConAppRedn`, etc. This means that other parts of the code won't have to worry about getting the orientations right (e.g. whether to use `mkCoherenceRightCo` or `mkCoherenceLeftCo`).sheafsheaf