GHC issueshttps://gitlab.haskell.org/ghc/ghc//issues20190707T18:00:18Zhttps://gitlab.haskell.org/ghc/ghc//issues/16381Regression: Implicitly kind variables not in scope20190707T18:00:18ZBen GamariRegression: Implicitly kind variables not in scopeOur new `head.hackage` CI infrastructure has caught its first regression, it seems. A number of packages now fail to build due to outofscope kind variables. For instance, `singletonbool`:
```
[1 of 1] Compiling Data.Singletons.Bool ( src/Data/Singletons/Bool.hs, dist/build/Data/Singletons/Bool.o )
*** Parser [Data.Singletons.Bool]:
Parser [Data.Singletons.Bool]: alloc=4264704 time=6.901
*** Renamer/typechecker [Data.Singletons.Bool]:
Renamer/typechecker [Data.Singletons.Bool]: alloc=17554720 time=92.794
src/Data/Singletons/Bool.hs:119:29: error:
Not in scope: type variable ‘k’

119  sboolEqRefl :: forall (a :: k) (b :: k). SBoolI (a == b) => Maybe (a :~: b)
 ^
src/Data/Singletons/Bool.hs:119:38: error:
Not in scope: type variable ‘k’

119  sboolEqRefl :: forall (a :: k) (b :: k). SBoolI (a == b) => Maybe (a :~: b)
 ^
```
<details><summary>Trac metadata</summary>
 Trac field  Value 
    
 Version  8.9 
 Type  Bug 
 TypeOfFailure  OtherFailure 
 Priority  highest 
 Resolution  Unresolved 
 Component  Compiler (Type checker) 
 Test case  
 Differential revisions  
 BlockedBy  
 Related  
 Blocking  
 CC  
 Operating system  
 Architecture  
</details>
<! {"blocked_by":[],"summary":"Regression: Implicitly kind variables not in scope","status":"New","operating_system":"","component":"Compiler (Type checker)","related":[],"milestone":"8.10.1","resolution":"Unresolved","owner":{"tag":"Unowned"},"version":"8.9","keywords":[],"differentials":[],"test_case":"","architecture":"","cc":[""],"type":"Bug","description":"Our new `head.hackage` CI infrastructure has caught its first regression, it seems. A number of packages now fail to build due to outofscope kind variables. For instance, `singletonbool`:\r\n{{{\r\n[1 of 1] Compiling Data.Singletons.Bool ( src/Data/Singletons/Bool.hs, dist/build/Data/Singletons/Bool.o )\r\n*** Parser [Data.Singletons.Bool]:\r\nParser [Data.Singletons.Bool]: alloc=4264704 time=6.901\r\n*** Renamer/typechecker [Data.Singletons.Bool]:\r\nRenamer/typechecker [Data.Singletons.Bool]: alloc=17554720 time=92.794\r\n\r\nsrc/Data/Singletons/Bool.hs:119:29: error:\r\n Not in scope: type variable ‘k’\r\n \r\n119  sboolEqRefl :: forall (a :: k) (b :: k). SBoolI (a == b) => Maybe (a :~: b)\r\n  ^\r\n\r\nsrc/Data/Singletons/Bool.hs:119:38: error:\r\n Not in scope: type variable ‘k’\r\n \r\n119  sboolEqRefl :: forall (a :: k) (b :: k). SBoolI (a == b) => Maybe (a :~: b)\r\n  ^\r\n}}}\r\n\r\n","type_of_failure":"OtherFailure","blocking":[]} >Our new `head.hackage` CI infrastructure has caught its first regression, it seems. A number of packages now fail to build due to outofscope kind variables. For instance, `singletonbool`:
```
[1 of 1] Compiling Data.Singletons.Bool ( src/Data/Singletons/Bool.hs, dist/build/Data/Singletons/Bool.o )
*** Parser [Data.Singletons.Bool]:
Parser [Data.Singletons.Bool]: alloc=4264704 time=6.901
*** Renamer/typechecker [Data.Singletons.Bool]:
Renamer/typechecker [Data.Singletons.Bool]: alloc=17554720 time=92.794
src/Data/Singletons/Bool.hs:119:29: error:
Not in scope: type variable ‘k’

119  sboolEqRefl :: forall (a :: k) (b :: k). SBoolI (a == b) => Maybe (a :~: b)
 ^
src/Data/Singletons/Bool.hs:119:38: error:
Not in scope: type variable ‘k’

119  sboolEqRefl :: forall (a :: k) (b :: k). SBoolI (a == b) => Maybe (a :~: b)
 ^
```
<details><summary>Trac metadata</summary>
 Trac field  Value 
    
 Version  8.9 
 Type  Bug 
 TypeOfFailure  OtherFailure 
 Priority  highest 
 Resolution  Unresolved 
 Component  Compiler (Type checker) 
 Test case  
 Differential revisions  
 BlockedBy  
 Related  
 Blocking  
 CC  
 Operating system  
 Architecture  
</details>
<! {"blocked_by":[],"summary":"Regression: Implicitly kind variables not in scope","status":"New","operating_system":"","component":"Compiler (Type checker)","related":[],"milestone":"8.10.1","resolution":"Unresolved","owner":{"tag":"Unowned"},"version":"8.9","keywords":[],"differentials":[],"test_case":"","architecture":"","cc":[""],"type":"Bug","description":"Our new `head.hackage` CI infrastructure has caught its first regression, it seems. A number of packages now fail to build due to outofscope kind variables. For instance, `singletonbool`:\r\n{{{\r\n[1 of 1] Compiling Data.Singletons.Bool ( src/Data/Singletons/Bool.hs, dist/build/Data/Singletons/Bool.o )\r\n*** Parser [Data.Singletons.Bool]:\r\nParser [Data.Singletons.Bool]: alloc=4264704 time=6.901\r\n*** Renamer/typechecker [Data.Singletons.Bool]:\r\nRenamer/typechecker [Data.Singletons.Bool]: alloc=17554720 time=92.794\r\n\r\nsrc/Data/Singletons/Bool.hs:119:29: error:\r\n Not in scope: type variable ‘k’\r\n \r\n119  sboolEqRefl :: forall (a :: k) (b :: k). SBoolI (a == b) => Maybe (a :~: b)\r\n  ^\r\n\r\nsrc/Data/Singletons/Bool.hs:119:38: error:\r\n Not in scope: type variable ‘k’\r\n \r\n119  sboolEqRefl :: forall (a :: k) (b :: k). SBoolI (a == b) => Maybe (a :~: b)\r\n  ^\r\n}}}\r\n\r\n","type_of_failure":"OtherFailure","blocking":[]} >8.10.1https://gitlab.haskell.org/ghc/ghc//issues/16391"Quantified type's kind mentions quantified type variable" error with fancyk...20200727T08:24:27ZRyan Scott"Quantified type's kind mentions quantified type variable" error with fancykinded GADTGiven the following:
```hs
{# LANGUAGE DataKinds #}
{# LANGUAGE GADTs #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE TypeFamilies #}
import Data.Kind
type Const (a :: Type) (b :: Type) = a
```
GHC happily accepts these definitions:
```hs
type family F :: Const Type a where
F = Int
type TS = (Int :: Const Type a)
```
However, the situation becomes murkier with data types. For some reason, GHC //rejects// this definition:
```hs
data T :: Const Type a where
MkT :: T
```
```
$ /opt/ghc/8.6.3/bin/ghc Bug.hs
[1 of 1] Compiling Main ( Bug.hs, Bug.o )
Bug.hs:14:3: error:
• Quantified type's kind mentions quantified type variable
(skolem escape)
type: forall a1. T
of kind: Const * a
• In the definition of data constructor ‘MkT’
In the data type declaration for ‘T’

14  MkT :: T
 ^^^^^^^^
```
I'm not quite sure how to interpret that error message, but it seems fishy to me. Even fishier is the fact that GHC //accepts// this slight modification of `T`:
```hs
data T2 :: Const Type a > Type where
MkT2 :: T2 b
```
Quite mysterious.

I briefly looked into where this error message is being thrown from. It turns out if you make this oneline change to GHC:
```diff
diff git a/compiler/typecheck/TcValidity.hs b/compiler/typecheck/TcValidity.hs
index 218f539c68..c7925767f9 100644
 a/compiler/typecheck/TcValidity.hs
+++ b/compiler/typecheck/TcValidity.hs
@@ 635,7 +635,7 @@ check_type ve@(ValidityEnv{ ve_tidy_env = env, ve_ctxt = ctxt
; check_type (ve{ve_tidy_env = env'}) tau
 Allow foralls to right of arrow
 ; checkTcM (not (any (`elemVarSet` tyCoVarsOfType phi_kind) tvs))
+ ; checkTcM (not (any (`elemVarSet` exactTyCoVarsOfType phi_kind) tvs))
(forAllEscapeErr env' ty tau_kind)
}
where
```
Then GHC will accept `T`. Whether this change is the right choice to make, I don't think I'm qualified to say.
<details><summary>Trac metadata</summary>
 Trac field  Value 
    
 Version  8.6.3 
 Type  Bug 
 TypeOfFailure  OtherFailure 
 Priority  normal 
 Resolution  Unresolved 
 Component  Compiler (Type checker) 
 Test case  
 Differential revisions  
 BlockedBy  
 Related  
 Blocking  
 CC  
 Operating system  
 Architecture  
</details>
<! {"blocked_by":[],"summary":"\"Quantified type's kind mentions quantified type variable\" error with fancykinded GADT","status":"New","operating_system":"","component":"Compiler (Type checker)","related":[],"milestone":"","resolution":"Unresolved","owner":{"tag":"Unowned"},"version":"8.6.3","keywords":["TypeInType"],"differentials":[],"test_case":"","architecture":"","cc":[""],"type":"Bug","description":"Given the following:\r\n\r\n{{{#!hs\r\n{# LANGUAGE DataKinds #}\r\n{# LANGUAGE GADTs #}\r\n{# LANGUAGE PolyKinds #}\r\n{# LANGUAGE TypeFamilies #}\r\n\r\nimport Data.Kind\r\n\r\ntype Const (a :: Type) (b :: Type) = a\r\n}}}\r\n\r\nGHC happily accepts these definitions:\r\n\r\n{{{#!hs\r\ntype family F :: Const Type a where\r\n F = Int\r\ntype TS = (Int :: Const Type a)\r\n}}}\r\n\r\nHowever, the situation becomes murkier with data types. For some reason, GHC //rejects// this definition:\r\n\r\n{{{#!hs\r\ndata T :: Const Type a where\r\n MkT :: T\r\n}}}\r\n{{{\r\n$ /opt/ghc/8.6.3/bin/ghc Bug.hs\r\n[1 of 1] Compiling Main ( Bug.hs, Bug.o )\r\n\r\nBug.hs:14:3: error:\r\n • Quantified type's kind mentions quantified type variable\r\n (skolem escape)\r\n type: forall a1. T\r\n of kind: Const * a\r\n • In the definition of data constructor ‘MkT’\r\n In the data type declaration for ‘T’\r\n \r\n14  MkT :: T\r\n  ^^^^^^^^\r\n}}}\r\n\r\nI'm not quite sure how to interpret that error message, but it seems fishy to me. Even fishier is the fact that GHC //accepts// this slight modification of `T`:\r\n\r\n{{{#!hs\r\ndata T2 :: Const Type a > Type where\r\n MkT2 :: T2 b\r\n}}}\r\n\r\nQuite mysterious.\r\n\r\n\r\n\r\nI briefly looked into where this error message is being thrown from. It turns out if you make this oneline change to GHC:\r\n\r\n{{{#!diff\r\ndiff git a/compiler/typecheck/TcValidity.hs b/compiler/typecheck/TcValidity.hs\r\nindex 218f539c68..c7925767f9 100644\r\n a/compiler/typecheck/TcValidity.hs\r\n+++ b/compiler/typecheck/TcValidity.hs\r\n@@ 635,7 +635,7 @@ check_type ve@(ValidityEnv{ ve_tidy_env = env, ve_ctxt = ctxt\r\n ; check_type (ve{ve_tidy_env = env'}) tau\r\n  Allow foralls to right of arrow\r\n\r\n ; checkTcM (not (any (`elemVarSet` tyCoVarsOfType phi_kind) tvs))\r\n+ ; checkTcM (not (any (`elemVarSet` exactTyCoVarsOfType phi_kind) tvs))\r\n (forAllEscapeErr env' ty tau_kind)\r\n }\r\n where\r\n}}}\r\n\r\nThen GHC will accept `T`. Whether this change is the right choice to make, I don't think I'm qualified to say.","type_of_failure":"OtherFailure","blocking":[]} >Given the following:
```hs
{# LANGUAGE DataKinds #}
{# LANGUAGE GADTs #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE TypeFamilies #}
import Data.Kind
type Const (a :: Type) (b :: Type) = a
```
GHC happily accepts these definitions:
```hs
type family F :: Const Type a where
F = Int
type TS = (Int :: Const Type a)
```
However, the situation becomes murkier with data types. For some reason, GHC //rejects// this definition:
```hs
data T :: Const Type a where
MkT :: T
```
```
$ /opt/ghc/8.6.3/bin/ghc Bug.hs
[1 of 1] Compiling Main ( Bug.hs, Bug.o )
Bug.hs:14:3: error:
• Quantified type's kind mentions quantified type variable
(skolem escape)
type: forall a1. T
of kind: Const * a
• In the definition of data constructor ‘MkT’
In the data type declaration for ‘T’

14  MkT :: T
 ^^^^^^^^
```
I'm not quite sure how to interpret that error message, but it seems fishy to me. Even fishier is the fact that GHC //accepts// this slight modification of `T`:
```hs
data T2 :: Const Type a > Type where
MkT2 :: T2 b
```
Quite mysterious.

I briefly looked into where this error message is being thrown from. It turns out if you make this oneline change to GHC:
```diff
diff git a/compiler/typecheck/TcValidity.hs b/compiler/typecheck/TcValidity.hs
index 218f539c68..c7925767f9 100644
 a/compiler/typecheck/TcValidity.hs
+++ b/compiler/typecheck/TcValidity.hs
@@ 635,7 +635,7 @@ check_type ve@(ValidityEnv{ ve_tidy_env = env, ve_ctxt = ctxt
; check_type (ve{ve_tidy_env = env'}) tau
 Allow foralls to right of arrow
 ; checkTcM (not (any (`elemVarSet` tyCoVarsOfType phi_kind) tvs))
+ ; checkTcM (not (any (`elemVarSet` exactTyCoVarsOfType phi_kind) tvs))
(forAllEscapeErr env' ty tau_kind)
}
where
```
Then GHC will accept `T`. Whether this change is the right choice to make, I don't think I'm qualified to say.
<details><summary>Trac metadata</summary>
 Trac field  Value 
    
 Version  8.6.3 
 Type  Bug 
 TypeOfFailure  OtherFailure 
 Priority  normal 
 Resolution  Unresolved 
 Component  Compiler (Type checker) 
 Test case  
 Differential revisions  
 BlockedBy  
 Related  
 Blocking  
 CC  
 Operating system  
 Architecture  
</details>
<! {"blocked_by":[],"summary":"\"Quantified type's kind mentions quantified type variable\" error with fancykinded GADT","status":"New","operating_system":"","component":"Compiler (Type checker)","related":[],"milestone":"","resolution":"Unresolved","owner":{"tag":"Unowned"},"version":"8.6.3","keywords":["TypeInType"],"differentials":[],"test_case":"","architecture":"","cc":[""],"type":"Bug","description":"Given the following:\r\n\r\n{{{#!hs\r\n{# LANGUAGE DataKinds #}\r\n{# LANGUAGE GADTs #}\r\n{# LANGUAGE PolyKinds #}\r\n{# LANGUAGE TypeFamilies #}\r\n\r\nimport Data.Kind\r\n\r\ntype Const (a :: Type) (b :: Type) = a\r\n}}}\r\n\r\nGHC happily accepts these definitions:\r\n\r\n{{{#!hs\r\ntype family F :: Const Type a where\r\n F = Int\r\ntype TS = (Int :: Const Type a)\r\n}}}\r\n\r\nHowever, the situation becomes murkier with data types. For some reason, GHC //rejects// this definition:\r\n\r\n{{{#!hs\r\ndata T :: Const Type a where\r\n MkT :: T\r\n}}}\r\n{{{\r\n$ /opt/ghc/8.6.3/bin/ghc Bug.hs\r\n[1 of 1] Compiling Main ( Bug.hs, Bug.o )\r\n\r\nBug.hs:14:3: error:\r\n • Quantified type's kind mentions quantified type variable\r\n (skolem escape)\r\n type: forall a1. T\r\n of kind: Const * a\r\n • In the definition of data constructor ‘MkT’\r\n In the data type declaration for ‘T’\r\n \r\n14  MkT :: T\r\n  ^^^^^^^^\r\n}}}\r\n\r\nI'm not quite sure how to interpret that error message, but it seems fishy to me. Even fishier is the fact that GHC //accepts// this slight modification of `T`:\r\n\r\n{{{#!hs\r\ndata T2 :: Const Type a > Type where\r\n MkT2 :: T2 b\r\n}}}\r\n\r\nQuite mysterious.\r\n\r\n\r\n\r\nI briefly looked into where this error message is being thrown from. It turns out if you make this oneline change to GHC:\r\n\r\n{{{#!diff\r\ndiff git a/compiler/typecheck/TcValidity.hs b/compiler/typecheck/TcValidity.hs\r\nindex 218f539c68..c7925767f9 100644\r\n a/compiler/typecheck/TcValidity.hs\r\n+++ b/compiler/typecheck/TcValidity.hs\r\n@@ 635,7 +635,7 @@ check_type ve@(ValidityEnv{ ve_tidy_env = env, ve_ctxt = ctxt\r\n ; check_type (ve{ve_tidy_env = env'}) tau\r\n  Allow foralls to right of arrow\r\n\r\n ; checkTcM (not (any (`elemVarSet` tyCoVarsOfType phi_kind) tvs))\r\n+ ; checkTcM (not (any (`elemVarSet` exactTyCoVarsOfType phi_kind) tvs))\r\n (forAllEscapeErr env' ty tau_kind)\r\n }\r\n where\r\n}}}\r\n\r\nThen GHC will accept `T`. Whether this change is the right choice to make, I don't think I'm qualified to say.","type_of_failure":"OtherFailure","blocking":[]} >8.10.1https://gitlab.haskell.org/ghc/ghc//issues/16394GHC internal error while typechecking of instance definition20190707T18:00:15ZDay1721GHC internal error while typechecking of instance definitionHello. \\\\
This code won't typecheck because of GHC internal error.
```hs
{# LANGUAGE PolyKinds, TypeFamilies, DataKinds #}
class C a where
type T (n :: a)
 vDIFFv
instance C a => C b => C (a, b) where
type T '(n, m) = (T n, T m)
```
with error message:
```
Bug.hs:7:10: error:
• GHC internal error: ‘T’ is not in scope during type checking, but it passed the renamer
tcl_env of environment: [a1LS :> Type variable ‘a’ = a :: *,
a1LT :> Type variable ‘b’ = b :: *]
• In the type instance declaration for ‘T’
In the instance declaration for ‘C b => C (a, b)’

7  type T (n, m) = (T n, T m)
 ^
Failed, no modules loaded.
```
but this works fine:
```hs
{# LANGUAGE PolyKinds, TypeFamilies, DataKinds #}
class C a where
type T (n :: a)
 vDIFFv
instance (C a, C b) => C (a, b) where
type T '(n, m) = (T n, T m)
```
Not sure is a bug, but either way it would be better to make more understandable error message
<details><summary>Trac metadata</summary>
 Trac field  Value 
    
 Version  8.6.3 
 Type  Bug 
 TypeOfFailure  OtherFailure 
 Priority  low 
 Resolution  Unresolved 
 Component  Compiler (Type checker) 
 Test case  
 Differential revisions  
 BlockedBy  
 Related  
 Blocking  
 CC  
 Operating system  
 Architecture  
</details>
<! {"blocked_by":[],"summary":"GHC internal error while typechecking of instance definition","status":"New","operating_system":"","component":"Compiler (Type checker)","related":[],"milestone":"","resolution":"Unresolved","owner":{"tag":"Unowned"},"version":"8.6.3","keywords":[],"differentials":[],"test_case":"","architecture":"","cc":[""],"type":"Bug","description":"Hello. \\\\\r\nThis code won't typecheck because of GHC internal error.\r\n\r\n{{{#!hs\r\n{# LANGUAGE PolyKinds, TypeFamilies, DataKinds #}\r\n\r\nclass C a where\r\n type T (n :: a)\r\n\r\n vDIFFv\r\ninstance C a => C b => C (a, b) where\r\n type T '(n, m) = (T n, T m)\r\n}}}\r\n\r\nwith error message: \r\n{{{\r\nBug.hs:7:10: error:\r\n • GHC internal error: ‘T’ is not in scope during type checking, but it passed the renamer\r\n tcl_env of environment: [a1LS :> Type variable ‘a’ = a :: *,\r\n a1LT :> Type variable ‘b’ = b :: *]\r\n • In the type instance declaration for ‘T’\r\n In the instance declaration for ‘C b => C (a, b)’\r\n \r\n7  type T (n, m) = (T n, T m)\r\n  ^\r\nFailed, no modules loaded.\r\n\r\n}}}\r\n\r\nbut this works fine:\r\n{{{#!hs\r\n{# LANGUAGE PolyKinds, TypeFamilies, DataKinds #}\r\n\r\nclass C a where\r\n type T (n :: a)\r\n\r\n vDIFFv\r\ninstance (C a, C b) => C (a, b) where\r\n type T '(n, m) = (T n, T m)\r\n}}}\r\n\r\nNot sure is a bug, but either way it would be better to make more understandable error message","type_of_failure":"OtherFailure","blocking":[]} >Hello. \\\\
This code won't typecheck because of GHC internal error.
```hs
{# LANGUAGE PolyKinds, TypeFamilies, DataKinds #}
class C a where
type T (n :: a)
 vDIFFv
instance C a => C b => C (a, b) where
type T '(n, m) = (T n, T m)
```
with error message:
```
Bug.hs:7:10: error:
• GHC internal error: ‘T’ is not in scope during type checking, but it passed the renamer
tcl_env of environment: [a1LS :> Type variable ‘a’ = a :: *,
a1LT :> Type variable ‘b’ = b :: *]
• In the type instance declaration for ‘T’
In the instance declaration for ‘C b => C (a, b)’

7  type T (n, m) = (T n, T m)
 ^
Failed, no modules loaded.
```
but this works fine:
```hs
{# LANGUAGE PolyKinds, TypeFamilies, DataKinds #}
class C a where
type T (n :: a)
 vDIFFv
instance (C a, C b) => C (a, b) where
type T '(n, m) = (T n, T m)
```
Not sure is a bug, but either way it would be better to make more understandable error message
<details><summary>Trac metadata</summary>
 Trac field  Value 
    
 Version  8.6.3 
 Type  Bug 
 TypeOfFailure  OtherFailure 
 Priority  low 
 Resolution  Unresolved 
 Component  Compiler (Type checker) 
 Test case  
 Differential revisions  
 BlockedBy  
 Related  
 Blocking  
 CC  
 Operating system  
 Architecture  
</details>
<! {"blocked_by":[],"summary":"GHC internal error while typechecking of instance definition","status":"New","operating_system":"","component":"Compiler (Type checker)","related":[],"milestone":"","resolution":"Unresolved","owner":{"tag":"Unowned"},"version":"8.6.3","keywords":[],"differentials":[],"test_case":"","architecture":"","cc":[""],"type":"Bug","description":"Hello. \\\\\r\nThis code won't typecheck because of GHC internal error.\r\n\r\n{{{#!hs\r\n{# LANGUAGE PolyKinds, TypeFamilies, DataKinds #}\r\n\r\nclass C a where\r\n type T (n :: a)\r\n\r\n vDIFFv\r\ninstance C a => C b => C (a, b) where\r\n type T '(n, m) = (T n, T m)\r\n}}}\r\n\r\nwith error message: \r\n{{{\r\nBug.hs:7:10: error:\r\n • GHC internal error: ‘T’ is not in scope during type checking, but it passed the renamer\r\n tcl_env of environment: [a1LS :> Type variable ‘a’ = a :: *,\r\n a1LT :> Type variable ‘b’ = b :: *]\r\n • In the type instance declaration for ‘T’\r\n In the instance declaration for ‘C b => C (a, b)’\r\n \r\n7  type T (n, m) = (T n, T m)\r\n  ^\r\nFailed, no modules loaded.\r\n\r\n}}}\r\n\r\nbut this works fine:\r\n{{{#!hs\r\n{# LANGUAGE PolyKinds, TypeFamilies, DataKinds #}\r\n\r\nclass C a where\r\n type T (n :: a)\r\n\r\n vDIFFv\r\ninstance (C a, C b) => C (a, b) where\r\n type T '(n, m) = (T n, T m)\r\n}}}\r\n\r\nNot sure is a bug, but either way it would be better to make more understandable error message","type_of_failure":"OtherFailure","blocking":[]} >8.8.1https://gitlab.haskell.org/ghc/ghc//issues/16418GHC internal error with strange scoping (GHC HEAD regression)20191108T20:46:21ZRyan ScottGHC internal error with strange scoping (GHC HEAD regression)The following program simply errors with GHC 8.6.4:
```haskell
{# LANGUAGE PolyKinds #}
{# LANGUAGE ScopedTypeVariables #}
module Bug where
import Data.Kind
data SameKind :: forall k. k > k > Type
f :: forall a k (b :: k). SameKind a b > ()
f = g
where
g :: SameKind a b > ()
g _ = ()
```
```
$ /opt/ghc/8.6.4/bin/ghc Bug.hs
[1 of 1] Compiling Bug ( Bug.hs, Bug.o )
Bug.hs:9:6: error:
• These kind and type variables: a k (b :: k)
are out of dependency order. Perhaps try this ordering:
k (a :: k) (b :: k)
• In the type signature:
f :: forall a k (b :: k). SameKind a b > ()

9  f :: forall a k (b :: k). SameKind a b > ()
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
On GHC HEAD, however, it throws a GHC internal error:
```
GHCi, version 8.9.20190309: https://www.haskell.org/ghc/ :? for help
Loaded GHCi configuration from /home/rgscott/.ghci
[1 of 1] Compiling Bug ( Bug.hs, interpreted )
Bug.hs:9:6: error:
• These kind and type variables: a k (b :: k)
are out of dependency order. Perhaps try this ordering:
k (a :: k) (b :: k)
• In the type signature:
f :: forall a k (b :: k). SameKind a b > ()

9  f :: forall a k (b :: k). SameKind a b > ()
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Bug.hs:12:19: error:
• GHC internal error: ‘a’ is not in scope during type checking, but it passed the renamer
tcl_env of environment: []
• In the first argument of ‘SameKind’, namely ‘a’
In the type signature: g :: SameKind a b > ()
In an equation for ‘f’:
f = g
where
g :: SameKind a b > ()
g _ = ()

12  g :: SameKind a b > ()
 ^
```The following program simply errors with GHC 8.6.4:
```haskell
{# LANGUAGE PolyKinds #}
{# LANGUAGE ScopedTypeVariables #}
module Bug where
import Data.Kind
data SameKind :: forall k. k > k > Type
f :: forall a k (b :: k). SameKind a b > ()
f = g
where
g :: SameKind a b > ()
g _ = ()
```
```
$ /opt/ghc/8.6.4/bin/ghc Bug.hs
[1 of 1] Compiling Bug ( Bug.hs, Bug.o )
Bug.hs:9:6: error:
• These kind and type variables: a k (b :: k)
are out of dependency order. Perhaps try this ordering:
k (a :: k) (b :: k)
• In the type signature:
f :: forall a k (b :: k). SameKind a b > ()

9  f :: forall a k (b :: k). SameKind a b > ()
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
On GHC HEAD, however, it throws a GHC internal error:
```
GHCi, version 8.9.20190309: https://www.haskell.org/ghc/ :? for help
Loaded GHCi configuration from /home/rgscott/.ghci
[1 of 1] Compiling Bug ( Bug.hs, interpreted )
Bug.hs:9:6: error:
• These kind and type variables: a k (b :: k)
are out of dependency order. Perhaps try this ordering:
k (a :: k) (b :: k)
• In the type signature:
f :: forall a k (b :: k). SameKind a b > ()

9  f :: forall a k (b :: k). SameKind a b > ()
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Bug.hs:12:19: error:
• GHC internal error: ‘a’ is not in scope during type checking, but it passed the renamer
tcl_env of environment: []
• In the first argument of ‘SameKind’, namely ‘a’
In the type signature: g :: SameKind a b > ()
In an equation for ‘f’:
f = g
where
g :: SameKind a b > ()
g _ = ()

12  g :: SameKind a b > ()
 ^
```8.10.1https://gitlab.haskell.org/ghc/ghc//issues/16422Inconsistent results with inaccessible code due to (~) vs. (~~)20210319T14:20:05ZRyan ScottInconsistent results with inaccessible code due to (~) vs. (~~)The following code typechecks:
```haskell
{# LANGUAGE GADTs #}
{# LANGUAGE TypeOperators #}
module Bug where
import Data.Type.Equality
data T = (Int ~ Char) => MkT { fld :: Int }
```
```
$ /opt/ghc/8.6.3/bin/ghci Bug.hs
GHCi, version 8.6.3: http://www.haskell.org/ghc/ :? for help
Loaded GHCi configuration from /home/rgscott/.ghci
[1 of 1] Compiling Bug ( Bug.hs, interpreted )
Bug.hs:7:32: warning: [Winaccessiblecode]
• Couldn't match type ‘Int’ with ‘Char’
Inaccessible code in
a pattern with constructor: MkT :: (Int ~ Char) => Int > T,
in an equation for ‘fld’
• In the pattern: MkT {fld = fld}
In an equation for ‘fld’: fld MkT {fld = fld} = fld

7  data T = (Int ~ Char) => MkT { fld :: Int }
 ^^^
```
It produces a warning, of course, since there's no way to ever actually invoke `fld`.
The interesting part of this is that if you replace `~` with `~~` in this program, then GHC will switch from accepting to rejecting it:
```haskell
data T = (Int ~~ Char) => MkT { fld :: Int }
```
```
$ /opt/ghc/8.6.3/bin/ghc Bug.hs
[1 of 1] Compiling Bug ( Bug.hs, Bug.o )
Bug.hs:7:10: error:
• Couldn't match expected type ‘Char’ with actual type ‘Int’
• In the ambiguity check for ‘MkT’
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
In the definition of data constructor ‘MkT’
In the data type declaration for ‘T’

7  data T = (Int ~~ Char) => MkT { fld :: Int }
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
This feels strangely inconsistent.

A similar phenomenon occurs in function definitions. This function is accepted (with no warnings):
```haskell
{# LANGUAGE GADTs #}
{# LANGUAGE TypeOperators #}
module Bug where
import Data.Type.Equality
f :: (Int ~ Char) => () > ()
f () = ()
```
But it is no longer accepted when `~` is swapped out with `~~`:
```haskell
f :: (Int ~~ Char) => () > ()
f () = ()
```
```
$ /opt/ghc/8.6.3/bin/ghc Bug.hs
[1 of 1] Compiling Bug ( Bug.hs, Bug.o )
Bug.hs:7:6: error:
• Couldn't match expected type ‘Char’ with actual type ‘Int’
• In the ambiguity check for ‘f’
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
In the type signature: f :: (Int ~~ Char) => () > ()

7  f :: (Int ~~ Char) => () > ()
 ^^^^^^^^^^^^^^^^^^^^^^^^^
```The following code typechecks:
```haskell
{# LANGUAGE GADTs #}
{# LANGUAGE TypeOperators #}
module Bug where
import Data.Type.Equality
data T = (Int ~ Char) => MkT { fld :: Int }
```
```
$ /opt/ghc/8.6.3/bin/ghci Bug.hs
GHCi, version 8.6.3: http://www.haskell.org/ghc/ :? for help
Loaded GHCi configuration from /home/rgscott/.ghci
[1 of 1] Compiling Bug ( Bug.hs, interpreted )
Bug.hs:7:32: warning: [Winaccessiblecode]
• Couldn't match type ‘Int’ with ‘Char’
Inaccessible code in
a pattern with constructor: MkT :: (Int ~ Char) => Int > T,
in an equation for ‘fld’
• In the pattern: MkT {fld = fld}
In an equation for ‘fld’: fld MkT {fld = fld} = fld

7  data T = (Int ~ Char) => MkT { fld :: Int }
 ^^^
```
It produces a warning, of course, since there's no way to ever actually invoke `fld`.
The interesting part of this is that if you replace `~` with `~~` in this program, then GHC will switch from accepting to rejecting it:
```haskell
data T = (Int ~~ Char) => MkT { fld :: Int }
```
```
$ /opt/ghc/8.6.3/bin/ghc Bug.hs
[1 of 1] Compiling Bug ( Bug.hs, Bug.o )
Bug.hs:7:10: error:
• Couldn't match expected type ‘Char’ with actual type ‘Int’
• In the ambiguity check for ‘MkT’
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
In the definition of data constructor ‘MkT’
In the data type declaration for ‘T’

7  data T = (Int ~~ Char) => MkT { fld :: Int }
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
This feels strangely inconsistent.

A similar phenomenon occurs in function definitions. This function is accepted (with no warnings):
```haskell
{# LANGUAGE GADTs #}
{# LANGUAGE TypeOperators #}
module Bug where
import Data.Type.Equality
f :: (Int ~ Char) => () > ()
f () = ()
```
But it is no longer accepted when `~` is swapped out with `~~`:
```haskell
f :: (Int ~~ Char) => () > ()
f () = ()
```
```
$ /opt/ghc/8.6.3/bin/ghc Bug.hs
[1 of 1] Compiling Bug ( Bug.hs, Bug.o )
Bug.hs:7:6: error:
• Couldn't match expected type ‘Char’ with actual type ‘Int’
• In the ambiguity check for ‘f’
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
In the type signature: f :: (Int ~~ Char) => () > ()

7  f :: (Int ~~ Char) => () > ()
 ^^^^^^^^^^^^^^^^^^^^^^^^^
```https://gitlab.haskell.org/ghc/ghc//issues/16436Pattern matching breaks injective type families20191221T17:31:05ZVladislav ZavialovPattern matching breaks injective type families```
{# LANGUAGE TypeFamilyDependencies, TypeOperators, DataKinds, GADTs, TypeApplications #}
data HList xs where
HNil :: HList '[]
HCons :: x > HList xs > HList (x:xs)
type family ListId xs = ys  ys > xs
where
ListId '[] = '[]
ListId (x:xs) = (x : ListId xs)
f :: HList (ListId ts) > ()
f a =
case a of
HNil > ()
 z@(HCons _ _) > f z  uncomment to break
z > f z
```
While `z > f z` works, pattern matching on `HCons` breaks it:
```
A.hs:16:24: error:
• Could not deduce: ListId xs ~ xs1
from the context: ListId ts ~ (x : xs1)
bound by a pattern with constructor:
HCons :: forall x (xs :: [*]). x > HList xs > HList (x : xs),
in a case alternative
at A.hs:16:816
‘xs1’ is a rigid type variable bound by
a pattern with constructor:
HCons :: forall x (xs :: [*]). x > HList xs > HList (x : xs),
in a case alternative
at A.hs:16:816
Expected type: HList (ListId (x : xs))
Actual type: HList (ListId ts)
• In the first argument of ‘f’, namely ‘z’
In the expression: f z
In a case alternative: z@(HCons _ _) > f z

16  z@(HCons _ _) > f z
 ^
``````
{# LANGUAGE TypeFamilyDependencies, TypeOperators, DataKinds, GADTs, TypeApplications #}
data HList xs where
HNil :: HList '[]
HCons :: x > HList xs > HList (x:xs)
type family ListId xs = ys  ys > xs
where
ListId '[] = '[]
ListId (x:xs) = (x : ListId xs)
f :: HList (ListId ts) > ()
f a =
case a of
HNil > ()
 z@(HCons _ _) > f z  uncomment to break
z > f z
```
While `z > f z` works, pattern matching on `HCons` breaks it:
```
A.hs:16:24: error:
• Could not deduce: ListId xs ~ xs1
from the context: ListId ts ~ (x : xs1)
bound by a pattern with constructor:
HCons :: forall x (xs :: [*]). x > HList xs > HList (x : xs),
in a case alternative
at A.hs:16:816
‘xs1’ is a rigid type variable bound by
a pattern with constructor:
HCons :: forall x (xs :: [*]). x > HList xs > HList (x : xs),
in a case alternative
at A.hs:16:816
Expected type: HList (ListId (x : xs))
Actual type: HList (ListId ts)
• In the first argument of ‘f’, namely ‘z’
In the expression: f z
In a case alternative: z@(HCons _ _) > f z

16  z@(HCons _ _) > f z
 ^
```https://gitlab.haskell.org/ghc/ghc//issues/16596Can't write instances of higherrank kinded variables20190519T18:33:57ZIcelandjackCan't write instances of higherrank kinded variables```haskell
{# language PolyKinds #}
{# language QuantifiedConstraints #}
{# language RankNTypes #}
import Data.Kind (Type)
class C (co :: forall k. k > Type)
instance C (co :: forall k. k > Type)
```
gives
```
$ ./ghcstage2 interactive ignoredotghci 1260_bug.hs
GHCi, version 8.7.20190211: https://www.haskell.org/ghc/ :? for help
[1 of 1] Compiling Main ( 1260_bug.hs, interpreted )
1260_bug.hs:8:13: error:
• Expected kind ‘forall k. k > *’, but ‘co’ has kind ‘k0’
• In the first argument of ‘C’, namely
‘(co :: forall k. k > Type)’
In the instance declaration for ‘C (co :: forall k. k > Type)’

8  instance C (co :: forall k. k > Type)
 ^^
Failed, no modules loaded.
Prelude>
```
Only the `instance` part causes trouble, should this work or not?```haskell
{# language PolyKinds #}
{# language QuantifiedConstraints #}
{# language RankNTypes #}
import Data.Kind (Type)
class C (co :: forall k. k > Type)
instance C (co :: forall k. k > Type)
```
gives
```
$ ./ghcstage2 interactive ignoredotghci 1260_bug.hs
GHCi, version 8.7.20190211: https://www.haskell.org/ghc/ :? for help
[1 of 1] Compiling Main ( 1260_bug.hs, interpreted )
1260_bug.hs:8:13: error:
• Expected kind ‘forall k. k > *’, but ‘co’ has kind ‘k0’
• In the first argument of ‘C’, namely
‘(co :: forall k. k > Type)’
In the instance declaration for ‘C (co :: forall k. k > Type)’

8  instance C (co :: forall k. k > Type)
 ^^
Failed, no modules loaded.
Prelude>
```
Only the `instance` part causes trouble, should this work or not?https://gitlab.haskell.org/ghc/ghc//issues/16609Only skip decls with CUSKs in kcLTyClDecl with PolyKinds on20201102T14:31:51ZNingning XieOnly skip decls with CUSKs in kcLTyClDecl with PolyKinds on# Summary
Data type kind checking skips decls with CUSKs in `kcLTyClDecl` (see note [Skip decls with CUSKs in kcLTyClDecl] in `TcTyClsDecls`).
However, when we have no PolyKinds, we shouldn't skip the check, because we have defaulting. Skipping won't bring us more polymorphism when we have defaulting.
WITHOUT any language extension, the following program is rejected nowadays.
```
data T1 a = MkT1 T2
data T2 = MkT2 (T1 Maybe)
```
What happened: `T1` and `T2` are in the same recursive group. Since `T2` has a CUSK (which is `Type`), `(T1 Maybe)` is skipped when kindchecking. So the kind of `a` remains unsolved and is thus defaulted to `Type`. Then `(T1 Maybe)` fails to typecheck because of a kind mismatch between `Type` and `Type > Type`.
The program typechecks in GHC 8.4 but fails to typecheck since GHC 8.6.
Propose: when we have NoPolyKinds, we don't skip the check; when we have PolyKinds, we skip the check.
# Steps to reproduce
Typecheck the example program.
# Expected behavior
The program should typecheck.
# Environment
* GHC version used: since 8.6# Summary
Data type kind checking skips decls with CUSKs in `kcLTyClDecl` (see note [Skip decls with CUSKs in kcLTyClDecl] in `TcTyClsDecls`).
However, when we have no PolyKinds, we shouldn't skip the check, because we have defaulting. Skipping won't bring us more polymorphism when we have defaulting.
WITHOUT any language extension, the following program is rejected nowadays.
```
data T1 a = MkT1 T2
data T2 = MkT2 (T1 Maybe)
```
What happened: `T1` and `T2` are in the same recursive group. Since `T2` has a CUSK (which is `Type`), `(T1 Maybe)` is skipped when kindchecking. So the kind of `a` remains unsolved and is thus defaulted to `Type`. Then `(T1 Maybe)` fails to typecheck because of a kind mismatch between `Type` and `Type > Type`.
The program typechecks in GHC 8.4 but fails to typecheck since GHC 8.6.
Propose: when we have NoPolyKinds, we don't skip the check; when we have PolyKinds, we skip the check.
# Steps to reproduce
Typecheck the example program.
# Expected behavior
The program should typecheck.
# Environment
* GHC version used: since 8.68.10.1https://gitlab.haskell.org/ghc/ghc//issues/16627Trouble resolving Typeable 'LiftedRep20210607T19:28:21ZDavid FeuerTrouble resolving Typeable 'LiftedRep# Summary
Inference fails with a simple `TypeRep` application.
# Steps to reproduce
```haskell
{# language TypeInType, ScopedTypeVariables #}
module Silly where
import Type.Reflection (Typeable, typeRep, TypeRep)
import Type.Reflection.Unsafe (mkTrApp)
import GHC.Exts (TYPE, RuntimeRep (..))
import Data.Kind (Type)
mkTrFun :: forall (r1 :: RuntimeRep) (r2 :: RuntimeRep)
(a :: TYPE r1) (b :: TYPE r2).
TypeRep a > TypeRep b > TypeRep ((a > b) :: Type)
mkTrFun a b = typeRep `mkTrApp` a `mkTrApp` b
```
# Expected behavior
I expected this to compile.
# Actual behavior
```
Silly.hs:11:15: error:
• No instance for (Typeable 'LiftedRep)
arising from a use of ‘typeRep’
• In the first argument of ‘mkTrApp’, namely ‘typeRep’
In the first argument of ‘mkTrApp’, namely ‘typeRep `mkTrApp` a’
In the expression: typeRep `mkTrApp` a `mkTrApp` b

11  mkTrFun a b = typeRep `mkTrApp` a `mkTrApp` b
 ^^^^^^^
```
This is a rather perplexing error, because `'LiftedRep` is most assuredly typeable.
# Environment
* GHC version used: 8.6.3
Optional:
* Operating System:
* System Architecture:# Summary
Inference fails with a simple `TypeRep` application.
# Steps to reproduce
```haskell
{# language TypeInType, ScopedTypeVariables #}
module Silly where
import Type.Reflection (Typeable, typeRep, TypeRep)
import Type.Reflection.Unsafe (mkTrApp)
import GHC.Exts (TYPE, RuntimeRep (..))
import Data.Kind (Type)
mkTrFun :: forall (r1 :: RuntimeRep) (r2 :: RuntimeRep)
(a :: TYPE r1) (b :: TYPE r2).
TypeRep a > TypeRep b > TypeRep ((a > b) :: Type)
mkTrFun a b = typeRep `mkTrApp` a `mkTrApp` b
```
# Expected behavior
I expected this to compile.
# Actual behavior
```
Silly.hs:11:15: error:
• No instance for (Typeable 'LiftedRep)
arising from a use of ‘typeRep’
• In the first argument of ‘mkTrApp’, namely ‘typeRep’
In the first argument of ‘mkTrApp’, namely ‘typeRep `mkTrApp` a’
In the expression: typeRep `mkTrApp` a `mkTrApp` b

11  mkTrFun a b = typeRep `mkTrApp` a `mkTrApp` b
 ^^^^^^^
```
This is a rather perplexing error, because `'LiftedRep` is most assuredly typeable.
# Environment
* GHC version used: 8.6.3
Optional:
* Operating System:
* System Architecture:https://gitlab.haskell.org/ghc/ghc//issues/16630Pass separation for TyClDecl LHS and RHS20190519T17:18:03ZVladislav ZavialovPass separation for TyClDecl LHS and RHSWhile implementing toplevel kind signatures, I faced an issue related to scoped kind variables. Here's an example:
```
type T :: forall k. k > Type
data T a = MkT (Proxy (a :: k))
```
When `XScopedTypeVariables` are on, we want `k` in `Proxy (a :: k)` to refer to `forall k.` in the TLKS.
Now, do we rename the signature or the data declaration first?
1. if we rename the declaration first, then `k` on its RHS won't be able to refer to `k` in the signature (`k` is not in scope)
2. if we rename the signature first, then it will not be able to refer to the declaration LHS (`T` is not in scope)
We have the exact same issue in terms, where it is solved by doing renaming in three steps:
1. rename the LHSs (`rnValBindsLHS`)
2. rename the signatures (`renameSigs`)
3. rename the RHSs (`rnValBindsRHS`)
In order to accommodate this design, `HsValBinds` and `HsBind` are parametrized by two separate passes:
```
data HsValBindsLR idL idR = ...
data HsBindLR idL idR = ...
```
On the other hand, renaming type/class declarations is done in one pass (`rnTyClDecls`), so `TyClDecl` is parametrized only by one pass:
```
data TyClDecl pass = ...
```
We should change this to:
```
data TyClDecl idL idR = ...
```
This is likely to be a fairly invasive change, so I'd rather do it independently from the TLKS implementation.While implementing toplevel kind signatures, I faced an issue related to scoped kind variables. Here's an example:
```
type T :: forall k. k > Type
data T a = MkT (Proxy (a :: k))
```
When `XScopedTypeVariables` are on, we want `k` in `Proxy (a :: k)` to refer to `forall k.` in the TLKS.
Now, do we rename the signature or the data declaration first?
1. if we rename the declaration first, then `k` on its RHS won't be able to refer to `k` in the signature (`k` is not in scope)
2. if we rename the signature first, then it will not be able to refer to the declaration LHS (`T` is not in scope)
We have the exact same issue in terms, where it is solved by doing renaming in three steps:
1. rename the LHSs (`rnValBindsLHS`)
2. rename the signatures (`renameSigs`)
3. rename the RHSs (`rnValBindsRHS`)
In order to accommodate this design, `HsValBinds` and `HsBind` are parametrized by two separate passes:
```
data HsValBindsLR idL idR = ...
data HsBindLR idL idR = ...
```
On the other hand, renaming type/class declarations is done in one pass (`rnTyClDecls`), so `TyClDecl` is parametrized only by one pass:
```
data TyClDecl pass = ...
```
We should change this to:
```
data TyClDecl idL idR = ...
```
This is likely to be a fairly invasive change, so I'd rather do it independently from the TLKS implementation.Vladislav ZavialovVladislav Zavialovhttps://gitlab.haskell.org/ghc/ghc//issues/16635Scoped kind variables are broken20190925T18:06:23ZVladislav ZavialovScoped kind variables are broken# Summary
This does work:
```haskell
 f :: [a > Either a ()]
f = [Left @a :: forall a. a > Either a ()]
````
This does not:
```haskell
 type F :: [a > Either a ()]
type F = '[Left @a :: forall a. a > Either a ()]
```
An unfortunate asymmetry between terms & types. See a related discussion at https://gitlab.haskell.org/ghc/ghc/wikis/ghckinds/kindinference/tlks
# Steps to reproduce
```
ghci> :set XScopedTypeVariables XDataKinds XPolyKinds XTypeApplications
ghci> type F = '[Left @a :: forall a. a > Either a ()]
<interactive>:3:18: error: Not in scope: type variable ‘a’
```
# Expected behavior
No error.
# Environment
* GHC version used: HEAD.# Summary
This does work:
```haskell
 f :: [a > Either a ()]
f = [Left @a :: forall a. a > Either a ()]
````
This does not:
```haskell
 type F :: [a > Either a ()]
type F = '[Left @a :: forall a. a > Either a ()]
```
An unfortunate asymmetry between terms & types. See a related discussion at https://gitlab.haskell.org/ghc/ghc/wikis/ghckinds/kindinference/tlks
# Steps to reproduce
```
ghci> :set XScopedTypeVariables XDataKinds XPolyKinds XTypeApplications
ghci> type F = '[Left @a :: forall a. a > Either a ()]
<interactive>:3:18: error: Not in scope: type variable ‘a’
```
# Expected behavior
No error.
# Environment
* GHC version used: HEAD.Vladislav ZavialovVladislav Zavialovhttps://gitlab.haskell.org/ghc/ghc//issues/16651incorrect typedefaults warning for lambda expressions20190519T16:57:39Zgeorge.colpittsincorrect typedefaults warning for lambda expressions# Summary
incorrect typedefaults warning for lambda expressions
# Steps to reproduce
load a file containing
```
{# OPTIONS_GHC Wtypedefaults #}
square = (\x > x * x)
square2 x = x * x
```
You will get the following:
>>>
alcm.hs:6:17: warning: [Wtypedefaults]
• Defaulting the following constraint to type ‘Integer’
Num a0 arising from a use of ‘*’
• In the expression: x * x
In the expression: (\ x > x * x)
In an equation for ‘square’: square = (\ x > x * x)

6  square = (\x > x * x)

>>>
# Expected behavior
There should be no warning for square just as there is no warning for square2
# Environment
* GHC version used: 8.6.5
Optional:
* Operating System: MacOS 10.14.4
* System Architecture:
# Summary
incorrect typedefaults warning for lambda expressions
# Steps to reproduce
load a file containing
```
{# OPTIONS_GHC Wtypedefaults #}
square = (\x > x * x)
square2 x = x * x
```
You will get the following:
>>>
alcm.hs:6:17: warning: [Wtypedefaults]
• Defaulting the following constraint to type ‘Integer’
Num a0 arising from a use of ‘*’
• In the expression: x * x
In the expression: (\ x > x * x)
In an equation for ‘square’: square = (\ x > x * x)

6  square = (\x > x * x)

>>>
# Expected behavior
There should be no warning for square just as there is no warning for square2
# Environment
* GHC version used: 8.6.5
Optional:
* Operating System: MacOS 10.14.4
* System Architecture:
https://gitlab.haskell.org/ghc/ghc//issues/16675Multiple occurrences of the same polykinded type don't unify20190531T16:14:15ZChristopher RodriguesMultiple occurrences of the same polykinded type don't unify# Summary
Multiple occurrences of the same polykinded type in a type signature are treated as distinct types, leading to type errors. Type inference creates different kind variables for each occurrence of the type, and won't unify them.
# Steps to reproduce
Compiling the following file, GHC reports an error.
~~~~haskell
{# LANGUAGE PolyKinds #}
{# OPTIONS_GHC fprintexplicitkinds #}
module Bug where
data Proxy a = P
data Indexed (f :: k > *) = I
idpi :: Indexed Proxy > Indexed Proxy
idpi x = x
~~~~
It infers the type `idpi :: forall k k1. Indexed k (Proxy k) > Indexed k1 (Proxy k1)`, and it reports an error at the expression `x` because it's returning the parameter type (with `k`) where the return type (with `k1`) is expected.
This is just a fancy id function, and I would have liked for GHC to infer `forall k. Indexed k (Proxy k) > Indexed k (Proxy k)`.
# Environment
* GHC version used: 8.6.5 (Stack lts13.22)# Summary
Multiple occurrences of the same polykinded type in a type signature are treated as distinct types, leading to type errors. Type inference creates different kind variables for each occurrence of the type, and won't unify them.
# Steps to reproduce
Compiling the following file, GHC reports an error.
~~~~haskell
{# LANGUAGE PolyKinds #}
{# OPTIONS_GHC fprintexplicitkinds #}
module Bug where
data Proxy a = P
data Indexed (f :: k > *) = I
idpi :: Indexed Proxy > Indexed Proxy
idpi x = x
~~~~
It infers the type `idpi :: forall k k1. Indexed k (Proxy k) > Indexed k1 (Proxy k1)`, and it reports an error at the expression `x` because it's returning the parameter type (with `k`) where the return type (with `k1`) is expected.
This is just a fancy id function, and I would have liked for GHC to infer `forall k. Indexed k (Proxy k) > Indexed k (Proxy k)`.
# Environment
* GHC version used: 8.6.5 (Stack lts13.22)https://gitlab.haskell.org/ghc/ghc//issues/16684Relax local equality check20190523T08:09:21ZIavor S. DiatchkiRelax local equality checkConsider the following example:
```haskell
{# Language RankNTypes, TypeFamilies #}
type family F a
q :: (forall b. (F b ~ Int) => (a,b)) > ()
q _ = ()
```
Currently GHC rejects this program as ambiguous. The reason is that during the ambiguity check, GHC needs to solve a constraint of the form:
```haskell
forall a. forall b. (F b ~ Int) => (a ~ alpha)
```
where `alpha` is a unification variable corresponding to the type parameter of `q` when used. At present, this constraint
cannot be solved, as the local assumption `F B ~ Int` causes `alpha` to be untouchable. In general, this is the safe thing to do, as in the presence of local assumptions unifying `alpha` with `a` might not be the most general solution (and, in fact, there may be *no* most general solution).
However, in this case it seems that the current rules are bit too conservative: the local assumption cannot affect the goal in any way, so `q` is not really ambiguous, and perhaps we can relax the current restrictions a bit. @simonpj proposed the following possible refinements [1]:
* (A) An implication is considered to “bind local equalities” iff it has at least one given equality whose free variables are not all bound by the same implication.
That loosens up `Note [Letbound skolems]` in `TcSMonad`, perhaps significantly. In particular, it woudl accept the example above.
The same email [1] proposed a second possiblity, (B), but it looks dodgy. So this ticket is about implementing (A).
References:
* [1] https://mail.haskell.org/pipermail/ghcdevs/2019May/017669.html
* [2] Note [Letbound skolems] in `TcSMonad`Consider the following example:
```haskell
{# Language RankNTypes, TypeFamilies #}
type family F a
q :: (forall b. (F b ~ Int) => (a,b)) > ()
q _ = ()
```
Currently GHC rejects this program as ambiguous. The reason is that during the ambiguity check, GHC needs to solve a constraint of the form:
```haskell
forall a. forall b. (F b ~ Int) => (a ~ alpha)
```
where `alpha` is a unification variable corresponding to the type parameter of `q` when used. At present, this constraint
cannot be solved, as the local assumption `F B ~ Int` causes `alpha` to be untouchable. In general, this is the safe thing to do, as in the presence of local assumptions unifying `alpha` with `a` might not be the most general solution (and, in fact, there may be *no* most general solution).
However, in this case it seems that the current rules are bit too conservative: the local assumption cannot affect the goal in any way, so `q` is not really ambiguous, and perhaps we can relax the current restrictions a bit. @simonpj proposed the following possible refinements [1]:
* (A) An implication is considered to “bind local equalities” iff it has at least one given equality whose free variables are not all bound by the same implication.
That loosens up `Note [Letbound skolems]` in `TcSMonad`, perhaps significantly. In particular, it woudl accept the example above.
The same email [1] proposed a second possiblity, (B), but it looks dodgy. So this ticket is about implementing (A).
References:
* [1] https://mail.haskell.org/pipermail/ghcdevs/2019May/017669.html
* [2] Note [Letbound skolems] in `TcSMonad`https://gitlab.haskell.org/ghc/ghc//issues/16687No test/assertion for kcLHsQTyVars_Cusk solveEqualities20190806T14:47:09ZVladislav ZavialovNo test/assertion for kcLHsQTyVars_Cusk solveEqualitiesIn `kcLHsQTyVars_Cusk`, there are these lines:
```
do { (scoped_kvs, (tc_tvs, res_kind))
< pushTcLevelM_ $
solveEqualities $
bindImplicitTKBndrs_Q_Skol kv_ns $
bindExplicitTKBndrs_Q_Skol ctxt_kind hs_tvs $
thing_inside
```
I'm using them as a model for the TLKS implementation, and right now I'm trying to understand what `solveEqualities` is doing here. So here's what I did:
1. I commented out the `solveEqualities $` line and ran the test suite. It did not cause any failures.
2. I did some git history digging and found out that this call was added in 55577a91 to fix #11648. From reading the discussion I figured that I need a `DDEBUG` compiler to see the error, as it's an assertion failure.
3. I've built GHC with the `devel2` flavour (it turns on `DDEBUG`) and ran the tests mentioned in #11648, there were no errors still. (Just to make sure that I have assertions enabled, I added `MASSERT(False)` and it failed)
Now I'm puzzled. What purpose does `solveEqualities` serve here? We need a test case that would fail without it!In `kcLHsQTyVars_Cusk`, there are these lines:
```
do { (scoped_kvs, (tc_tvs, res_kind))
< pushTcLevelM_ $
solveEqualities $
bindImplicitTKBndrs_Q_Skol kv_ns $
bindExplicitTKBndrs_Q_Skol ctxt_kind hs_tvs $
thing_inside
```
I'm using them as a model for the TLKS implementation, and right now I'm trying to understand what `solveEqualities` is doing here. So here's what I did:
1. I commented out the `solveEqualities $` line and ran the test suite. It did not cause any failures.
2. I did some git history digging and found out that this call was added in 55577a91 to fix #11648. From reading the discussion I figured that I need a `DDEBUG` compiler to see the error, as it's an assertion failure.
3. I've built GHC with the `devel2` flavour (it turns on `DDEBUG`) and ran the tests mentioned in #11648, there were no errors still. (Just to make sure that I have assertions enabled, I added `MASSERT(False)` and it failed)
Now I'm puzzled. What purpose does `solveEqualities` serve here? We need a test case that would fail without it!⊥Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/16693Order of declarations affects which programs are accepted (type families and ...20200123T19:39:43ZIavor S. DiatchkiOrder of declarations affects which programs are accepted (type families and existentials)Consider the following example:
```haskell
{# LANGUAGE ExistentialQuantification, TypeFamilies #}
module Bug where
type family G n
type instance G a = F
data T = forall w. T (G w)
type family F where F = ()
 type family G n
```
GHC rejects this program, when checking if `T` is ambiguous. However, if I move the declaration of `G` to the end of the file (the declaration that is commented out), then GHC accepts the program.
I would guess that, somehow, it matters in what order things are processedif `G` is evaluated fully first, it can resolve to `()` and there is no ambiguity. However, if `G` is not evaluated, then there appears to be an ambiguity as `w` occurs under a type family.Consider the following example:
```haskell
{# LANGUAGE ExistentialQuantification, TypeFamilies #}
module Bug where
type family G n
type instance G a = F
data T = forall w. T (G w)
type family F where F = ()
 type family G n
```
GHC rejects this program, when checking if `T` is ambiguous. However, if I move the declaration of `G` to the end of the file (the declaration that is commented out), then GHC accepts the program.
I would guess that, somehow, it matters in what order things are processedif `G` is evaluated fully first, it can resolve to `()` and there is no ambiguity. However, if `G` is not evaluated, then there appears to be an ambiguity as `w` occurs under a type family.Vladislav ZavialovVladislav Zavialovhttps://gitlab.haskell.org/ghc/ghc//issues/16735Prevent `rewriteEvidence` from converting a W into a WD20200123T19:39:43ZnfrisbyPrevent `rewriteEvidence` from converting a W into a WD# Summary
(This is true in 8.6.5 and also right now at 6febc444c0abea6c033174aa0e813c950b9b2877.)
https://gitlab.haskell.org/ghc/ghc/blob/master/compiler/typecheck/TcCanonical.hs#L2226 declares `rewriteEvidence` with the comment that "rewriteEvidence old_ev new_pred co ... Returns a new_ev : new_pred, with same wanted/given/derived flag as old_ev".
However, the `CtWanted` case just immediately calls `newWanted`, which ignores the incoming `ctev_nosh` flag and always uses `WDeriv`.
```
rewriteEvidence ev@(CtWanted { ctev_dest = dest
, ctev_loc = loc }) new_pred co
= do { mb_new_ev < newWanted loc new_pred
```
Thus I'm seeing a `[W]` become a `[WD]`, which seems to contradict the comment's "same flag" claim.
# Steps to reproduce
Unfortunately, my only repro involves a plugin I'm developing. The constraint solver is looping unproductively because my plugin keeps discarding the (re)emitted `[D]` shadow as a tautology, then the [W] "unsplits" during canonicalization (even though my plugin didn't touch the `[W]`), this reemits the same `[D]` (via a fundep), and so on.
(See the `ddumptctrace` snippet in first comment below.)
# Expected behavior
`rewriteEvidence` should create a `[W]` from a `[W]`.
# Environment
* GHC version used: GHC8.6.5# Summary
(This is true in 8.6.5 and also right now at 6febc444c0abea6c033174aa0e813c950b9b2877.)
https://gitlab.haskell.org/ghc/ghc/blob/master/compiler/typecheck/TcCanonical.hs#L2226 declares `rewriteEvidence` with the comment that "rewriteEvidence old_ev new_pred co ... Returns a new_ev : new_pred, with same wanted/given/derived flag as old_ev".
However, the `CtWanted` case just immediately calls `newWanted`, which ignores the incoming `ctev_nosh` flag and always uses `WDeriv`.
```
rewriteEvidence ev@(CtWanted { ctev_dest = dest
, ctev_loc = loc }) new_pred co
= do { mb_new_ev < newWanted loc new_pred
```
Thus I'm seeing a `[W]` become a `[WD]`, which seems to contradict the comment's "same flag" claim.
# Steps to reproduce
Unfortunately, my only repro involves a plugin I'm developing. The constraint solver is looping unproductively because my plugin keeps discarding the (re)emitted `[D]` shadow as a tautology, then the [W] "unsplits" during canonicalization (even though my plugin didn't touch the `[W]`), this reemits the same `[D]` (via a fundep), and so on.
(See the `ddumptctrace` snippet in first comment below.)
# Expected behavior
`rewriteEvidence` should create a `[W]` from a `[W]`.
# Environment
* GHC version used: GHC8.6.5https://gitlab.haskell.org/ghc/ghc//issues/16767Quantification by level numbers would fail20191014T12:51:46ZRichard Eisenbergrae@richarde.devQuantification by level numbers would failWitness:
```
rae:11:43:10 ~/ghc/ghchead/testsuite/tests> ~/ghc/ghchead/inplace/bin/ghcstage2 interactive fprintexplicitforalls fprintexplicitkinds XTypeApplications XDataKinds
GHCi, version 8.9.0.20190531: https://www.haskell.org/ghc/ :? for help
Loaded GHCi configuration from /Users/rae/.ghc/ghci.conf
Prelude> import Data.Proxy
Prelude Data.Proxy> :kind! 'Proxy @_
WARNING: file compiler/typecheck/TcMType.hs, line 1470
Quantification by level numbers would fail
Outer level = 0
dep_tkvs = {k_a1Ef[tau:0], __a1Eh[tau:0]}
co_vars =
co_tvs = {}
dep_kvs = [k_a1Ef[tau:0], __a1Eh[tau:0]]
dep_kvs2 = []
nondep_tvs = []
nondep_tvs2 = []
Call stack:
CallStack (from HasCallStack):
callStackDoc, called at compiler/utils/Outputable.hs:1231:29 in ghc:Outputable
warnPprTrace, called at compiler/typecheck/TcMType.hs:1470:11 in ghc:TcMType
'Proxy @_ :: forall {k} {_ :: k}. Proxy @{k} _
= 'Proxy @{k} @_
Prelude Data.Proxy>
```
The problem is that `tcRnType` (the worker for GHCi's `:kind`) does not bump the level before doing its work. Will fix in ongoing work (!951).Witness:
```
rae:11:43:10 ~/ghc/ghchead/testsuite/tests> ~/ghc/ghchead/inplace/bin/ghcstage2 interactive fprintexplicitforalls fprintexplicitkinds XTypeApplications XDataKinds
GHCi, version 8.9.0.20190531: https://www.haskell.org/ghc/ :? for help
Loaded GHCi configuration from /Users/rae/.ghc/ghci.conf
Prelude> import Data.Proxy
Prelude Data.Proxy> :kind! 'Proxy @_
WARNING: file compiler/typecheck/TcMType.hs, line 1470
Quantification by level numbers would fail
Outer level = 0
dep_tkvs = {k_a1Ef[tau:0], __a1Eh[tau:0]}
co_vars =
co_tvs = {}
dep_kvs = [k_a1Ef[tau:0], __a1Eh[tau:0]]
dep_kvs2 = []
nondep_tvs = []
nondep_tvs2 = []
Call stack:
CallStack (from HasCallStack):
callStackDoc, called at compiler/utils/Outputable.hs:1231:29 in ghc:Outputable
warnPprTrace, called at compiler/typecheck/TcMType.hs:1470:11 in ghc:TcMType
'Proxy @_ :: forall {k} {_ :: k}. Proxy @{k} _
= 'Proxy @{k} @_
Prelude Data.Proxy>
```
The problem is that `tcRnType` (the worker for GHCi's `:kind`) does not bump the level before doing its work. Will fix in ongoing work (!951).Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/16775Don't zap naughty quantification candidates: error instead20201215T12:32:56ZRichard Eisenbergrae@richarde.devDon't zap naughty quantification candidates: error insteadNote [Naughty quantification candidates] in TcMType describes a scenario like `forall arg. ... (alpha[tau] :: arg) ...`, where `alpha`, a unification variable, has a bound skolem in its type. If `alpha` is otherwise unconstrained, we simply don't know what to do with it. So, as the Note explains, we zap it to `Any`.
However, we recently decided not to `Any`ify in type declarations. And I think we are wrong to `Any`ify here, too. We should just error. If not, we risk having `Any` leak in error messages, and it seems a nice goal not to ever let users see `Any` (short of TH or reflection or other dastardly deeds).
The example is `partialsigs/should_fail/T14040a`. You can find the program in question at the top of #14040. https://gitlab.haskell.org/ghc/ghc/issues/14040#note_168778 reports HEAD's error message. (The program and error message are all very intricate. Don't get distracted by reading them.) However, some of the wildcards in that error message have locallybound types, meaning there is no hope for them, regardless of other errors about. In other work (some refactoring to be posted soon), I spotted that `tcHsPartialSigType` was missing out on the action in Note [Naughty quantification candidates] and so fixed the problem. This means that the error for that program now mentions `Any`.
Here is a simpler test case:
```
foo :: forall (f :: forall a (b :: a > Type). b _). f _
foo = foo
```
Note that the type of the first `_` must be `a`, which is locally quantified. In HEAD, this program trips an assertion failure around the substitution invariant (and I have not investigated further). In my branch that duly checks partial signatures for naught quantification candidates, we get
```
• Expected kind ‘k > *’, but ‘f’ has kind ‘k > Any @*’
• In the type ‘f _’
In the type signature:
foo :: forall (f :: forall a (b :: a > Type). b _). f _
```
This is correct enough, but there's `Any` in the error message. I think it would be much better just to reject the type signature a priori.
If I make the program correct (by wrapping the `f _` in a call to `Proxy`, I get
```
Scratch.hs:44:50: warning: [Wpartialtypesignatures]
• Found type wildcard ‘_’ standing for ‘Any @a :: a’
Where: ‘a’ is a rigid type variable bound by
‘forall a (b :: a > Type). b _’
at Scratch.hs:44:28
• In the first argument of ‘b’, namely ‘_’
In the kind ‘forall a (b :: a > Type). b _’
In the type signature:
foo :: forall (f :: forall a (b :: a > Type). b _). Proxy (f _)

44  foo :: forall (f :: forall a (b :: a > Type). b _). Proxy (f _)
 ^
Scratch.hs:44:63: warning: [Wpartialtypesignatures]
• Found type wildcard ‘_’ standing for ‘_ :: k’
Where: ‘k’, ‘_’ are rigid type variables bound by
the inferred type of
foo :: Proxy
@{Any @Type} (f @Type @((>) @{'LiftedRep} @{'LiftedRep} k) _)
at Scratch.hs:45:19
• In the first argument of ‘f’, namely ‘_’
In the first argument of ‘Proxy’, namely ‘(f _)’
In the type ‘Proxy (f _)’

44  foo :: forall (f :: forall a (b :: a > Type). b _). Proxy (f _)
 ^
```
More `Any`s. No! Reject!
What think you (for any value of you)?Note [Naughty quantification candidates] in TcMType describes a scenario like `forall arg. ... (alpha[tau] :: arg) ...`, where `alpha`, a unification variable, has a bound skolem in its type. If `alpha` is otherwise unconstrained, we simply don't know what to do with it. So, as the Note explains, we zap it to `Any`.
However, we recently decided not to `Any`ify in type declarations. And I think we are wrong to `Any`ify here, too. We should just error. If not, we risk having `Any` leak in error messages, and it seems a nice goal not to ever let users see `Any` (short of TH or reflection or other dastardly deeds).
The example is `partialsigs/should_fail/T14040a`. You can find the program in question at the top of #14040. https://gitlab.haskell.org/ghc/ghc/issues/14040#note_168778 reports HEAD's error message. (The program and error message are all very intricate. Don't get distracted by reading them.) However, some of the wildcards in that error message have locallybound types, meaning there is no hope for them, regardless of other errors about. In other work (some refactoring to be posted soon), I spotted that `tcHsPartialSigType` was missing out on the action in Note [Naughty quantification candidates] and so fixed the problem. This means that the error for that program now mentions `Any`.
Here is a simpler test case:
```
foo :: forall (f :: forall a (b :: a > Type). b _). f _
foo = foo
```
Note that the type of the first `_` must be `a`, which is locally quantified. In HEAD, this program trips an assertion failure around the substitution invariant (and I have not investigated further). In my branch that duly checks partial signatures for naught quantification candidates, we get
```
• Expected kind ‘k > *’, but ‘f’ has kind ‘k > Any @*’
• In the type ‘f _’
In the type signature:
foo :: forall (f :: forall a (b :: a > Type). b _). f _
```
This is correct enough, but there's `Any` in the error message. I think it would be much better just to reject the type signature a priori.
If I make the program correct (by wrapping the `f _` in a call to `Proxy`, I get
```
Scratch.hs:44:50: warning: [Wpartialtypesignatures]
• Found type wildcard ‘_’ standing for ‘Any @a :: a’
Where: ‘a’ is a rigid type variable bound by
‘forall a (b :: a > Type). b _’
at Scratch.hs:44:28
• In the first argument of ‘b’, namely ‘_’
In the kind ‘forall a (b :: a > Type). b _’
In the type signature:
foo :: forall (f :: forall a (b :: a > Type). b _). Proxy (f _)

44  foo :: forall (f :: forall a (b :: a > Type). b _). Proxy (f _)
 ^
Scratch.hs:44:63: warning: [Wpartialtypesignatures]
• Found type wildcard ‘_’ standing for ‘_ :: k’
Where: ‘k’, ‘_’ are rigid type variables bound by
the inferred type of
foo :: Proxy
@{Any @Type} (f @Type @((>) @{'LiftedRep} @{'LiftedRep} k) _)
at Scratch.hs:45:19
• In the first argument of ‘f’, namely ‘_’
In the first argument of ‘Proxy’, namely ‘(f _)’
In the type ‘Proxy (f _)’

44  foo :: forall (f :: forall a (b :: a > Type). b _). Proxy (f _)
 ^
```
More `Any`s. No! Reject!
What think you (for any value of you)?8.8.2https://gitlab.haskell.org/ghc/ghc//issues/16786GHC suggests that infix operators might have the wrong number of arguments20190707T18:00:03ZChris SmithGHC suggests that infix operators might have the wrong number of arguments# Summary
GHC sometimes suggests that you have passed the wrong number of arguments to an infix operator.
# Steps to reproduce
Compile this code with GHC 8.6.5:
answer = map (foo ++ bar) "hello, world"
foo = toUpper
bar = take 10
The first error message says:
Test.hs:1:15: error:
• Couldn't match expected type ‘Char > b’ with actual type ‘[a1]’
• Possible cause: ‘(++)’ is applied to too many arguments
In the first argument of ‘map’, namely ‘(foo ++ bar)’
In the expression: map (foo ++ bar) "hello, world"
In an equation for ‘answer’:
answer = map (foo ++ bar) "hello, world"
• Relevant bindings include answer :: [b] (bound at Test.hs:1:1)
The suggestion that I have applied (++) to too many arguments is not a very likely one, since infix operators must take two arguments just by their syntax alone. I suppose it's possible that I intended to write an operator section, but it seems like a stretch.
# Expected behavior
I would expect this error message without the suggest that (++) is applied to too many arguments.
# Environment
* GHC version used: 8.6.5# Summary
GHC sometimes suggests that you have passed the wrong number of arguments to an infix operator.
# Steps to reproduce
Compile this code with GHC 8.6.5:
answer = map (foo ++ bar) "hello, world"
foo = toUpper
bar = take 10
The first error message says:
Test.hs:1:15: error:
• Couldn't match expected type ‘Char > b’ with actual type ‘[a1]’
• Possible cause: ‘(++)’ is applied to too many arguments
In the first argument of ‘map’, namely ‘(foo ++ bar)’
In the expression: map (foo ++ bar) "hello, world"
In an equation for ‘answer’:
answer = map (foo ++ bar) "hello, world"
• Relevant bindings include answer :: [b] (bound at Test.hs:1:1)
The suggestion that I have applied (++) to too many arguments is not a very likely one, since infix operators must take two arguments just by their syntax alone. I suppose it's possible that I intended to write an operator section, but it seems like a stretch.
# Expected behavior
I would expect this error message without the suggest that (++) is applied to too many arguments.
# Environment
* GHC version used: 8.6.5⊥https://gitlab.haskell.org/ghc/ghc//issues/16877GHCi panics using fdefertypeerrors when pattern matching on types with mul...20200218T12:30:12ZBerengalGHCi panics using fdefertypeerrors when pattern matching on types with multiple constructors using outofscope variables# Summary
With fdefertypeerrors enabled GHCi will panic on certain errors involving pattern matching on types with multiple constructors. At least as far as I can tell.
# Steps to reproduce
The following is the smallest module I could find that causes the panic:
```
foo = x
where (x:xs) = bar
```
GHCi command and output:
```
▶ ghci ignoredotghci fdefertypeerrors Foo.hs
GHCi, version 8.6.5: http://www.haskell.org/ghc/ :? for help
[1 of 1] Compiling Main ( Foo.hs, interpreted )
Foo.hs:2:18: warning: [Wdeferredoutofscopevariables]
Variable not in scope: bar :: [a1]

2  where (x:xs) = bar
 ^^^
ghc: panic! (the 'impossible' happened)
(GHC version 8.6.5 for x86_64unknownlinux):
getIdFromTrivialExpr
\ (@ a_a1x4) > case ds_s1yU @ a_a1x4 of wild_Xb { }
Call stack:
CallStack (from HasCallStack):
callStackDoc, called at compiler/utils/Outputable.hs:1160:37 in ghc:Outputable
pprPanic, called at compiler/coreSyn/CoreUtils.hs:977:18 in ghc:CoreUtils
Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug
>
```
The equivalent using `let` also panics. The pattern match in the where is neccessary, as is using a matched variable in the main expression (either one will do). Matching on a tuple does not cause a panic, nor does matching on `data Foo a = Foo a a`, but matching on `data Foo a = Foo a a  Bar a a` panics regardless of which constructor is chosen.
# Expected behavior
GHCi doesn't panic, but either loads the module correctly or explains why it can't do so.
# Environment
* GHC version used: 8.6.5
Optional:
* Operating System: Archlinux
* System Architecture: x86_64# Summary
With fdefertypeerrors enabled GHCi will panic on certain errors involving pattern matching on types with multiple constructors. At least as far as I can tell.
# Steps to reproduce
The following is the smallest module I could find that causes the panic:
```
foo = x
where (x:xs) = bar
```
GHCi command and output:
```
▶ ghci ignoredotghci fdefertypeerrors Foo.hs
GHCi, version 8.6.5: http://www.haskell.org/ghc/ :? for help
[1 of 1] Compiling Main ( Foo.hs, interpreted )
Foo.hs:2:18: warning: [Wdeferredoutofscopevariables]
Variable not in scope: bar :: [a1]

2  where (x:xs) = bar
 ^^^
ghc: panic! (the 'impossible' happened)
(GHC version 8.6.5 for x86_64unknownlinux):
getIdFromTrivialExpr
\ (@ a_a1x4) > case ds_s1yU @ a_a1x4 of wild_Xb { }
Call stack:
CallStack (from HasCallStack):
callStackDoc, called at compiler/utils/Outputable.hs:1160:37 in ghc:Outputable
pprPanic, called at compiler/coreSyn/CoreUtils.hs:977:18 in ghc:CoreUtils
Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug
>
```
The equivalent using `let` also panics. The pattern match in the where is neccessary, as is using a matched variable in the main expression (either one will do). Matching on a tuple does not cause a panic, nor does matching on `data Foo a = Foo a a`, but matching on `data Foo a = Foo a a  Bar a a` panics regardless of which constructor is chosen.
# Expected behavior
GHCi doesn't panic, but either loads the module correctly or explains why it can't do so.
# Environment
* GHC version used: 8.6.5
Optional:
* Operating System: Archlinux
* System Architecture: x86_648.8.2https://gitlab.haskell.org/ghc/ghc//issues/16887GHC panic: "StgCmmEnv: variable not found"  Something with MonoLocalBinds, t...20201114T10:00:44ZBerengalGHC panic: "StgCmmEnv: variable not found"  Something with MonoLocalBinds, type inference and fdefertypeerrors# Summary
GHC panics on some modules with GADTs enabled, top level declarations without type annotations and fdefertypeerrors enabled.
# Steps to reproduce
The smallest module I could find to trigger the bug:
```
{# LANGUAGE GADTs #}
breaks = pure "anything polymorphic"
main = do
putStrLn "could be anything"
breaks
putStrLn "also could be anything"
```
Command and output:
```
▶ ghc fdefertypeerrors Panic.hs
[1 of 1] Compiling Main ( Panic.hs, Panic.o )
ghc: panic! (the 'impossible' happened)
(GHC version 8.6.5 for x86_64unknownlinux):
StgCmmEnv: variable not found
$dMonad_a1ce
local binds for:
$trModule
whatever_rq4
$trModule1_r1p6
$trModule2_r1pj
$trModule3_r1pk
$trModule4_r1pl
sat_s1rx
Call stack:
CallStack (from HasCallStack):
callStackDoc, called at compiler/utils/Outputable.hs:1160:37 in ghc:Outputable
pprPanic, called at compiler/codeGen/StgCmmEnv.hs:149:9 in ghc:StgCmmEnv
Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug
```
This compiles fine without `fdefertypeerrors`, or with type signatures for either `breaks` or `main`, or without GADTs enabled. GHCi loads the module without problem, but panics whenever it needs to use any symbol from the module, including unrelated symbols.
# Expected behavior
I expect GHC not to panic.
# Environment
* GHC version used: 8.6.5
Optional:
* Operating System: Arch linux
* System Architecture: x86_64# Summary
GHC panics on some modules with GADTs enabled, top level declarations without type annotations and fdefertypeerrors enabled.
# Steps to reproduce
The smallest module I could find to trigger the bug:
```
{# LANGUAGE GADTs #}
breaks = pure "anything polymorphic"
main = do
putStrLn "could be anything"
breaks
putStrLn "also could be anything"
```
Command and output:
```
▶ ghc fdefertypeerrors Panic.hs
[1 of 1] Compiling Main ( Panic.hs, Panic.o )
ghc: panic! (the 'impossible' happened)
(GHC version 8.6.5 for x86_64unknownlinux):
StgCmmEnv: variable not found
$dMonad_a1ce
local binds for:
$trModule
whatever_rq4
$trModule1_r1p6
$trModule2_r1pj
$trModule3_r1pk
$trModule4_r1pl
sat_s1rx
Call stack:
CallStack (from HasCallStack):
callStackDoc, called at compiler/utils/Outputable.hs:1160:37 in ghc:Outputable
pprPanic, called at compiler/codeGen/StgCmmEnv.hs:149:9 in ghc:StgCmmEnv
Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug
```
This compiles fine without `fdefertypeerrors`, or with type signatures for either `breaks` or `main`, or without GADTs enabled. GHCi loads the module without problem, but panics whenever it needs to use any symbol from the module, including unrelated symbols.
# Expected behavior
I expect GHC not to panic.
# Environment
* GHC version used: 8.6.5
Optional:
* Operating System: Arch linux
* System Architecture: x86_64https://gitlab.haskell.org/ghc/ghc//issues/16894TypeError hides a second error message20200123T19:40:11ZJoey HessTypeError hides a second error message# Summary
Using TypeError seems to hide other type error messages due to eg, bad arguments passed to a function.
# Steps to reproduce
Load into ghci:
```
{# LANGUAGE DataKinds, UndecidableInstances, TypeFamilies #}
import GHC.TypeLits
type family Check x :: Bool where
Check 'True = 'True
Check x = 'False
foo :: Check 'False ~ 'True => Int > String
foo n = "never reached"
type family Check2 x :: Bool where
Check2 'True = 'True
Check2 x = TypeError ('Text "no")
foo2 :: Check2 'False ~ 'True => Int > String
foo2 n = "never reached"
```
```
ghci> foo "bar"
<interactive>:69:1: error:
• Couldn't match type ‘'False’ with ‘'True’
arising from a use of ‘foo’
• In the expression: foo "bar"
In an equation for ‘it’: it = foo "bar"
<interactive>:69:5: error:
• Couldn't match expected type ‘Int’ with actual type ‘[Char]’
• In the first argument of ‘foo’, namely ‘"bar"’
In the expression: foo "bar"
In an equation for ‘it’: it = foo "bar"
ghci> foo2 "bar"
<interactive>:70:1: error:
• no
• In the expression: foo2 "bar"
In an equation for ‘it’: it = foo2 "bar"
```
# Expected behavior
I expected to see the same error about Int vs [Char] for foo2 as is shown for foo, as well as the custom TypeError. However, the use of TypeError somehow prevents the Int vs [Char] error from being displayed.
This is preventing me from using TypeError in situations where there might be another, more basic
type error in the same code.
This may be related to https://gitlab.haskell.org/ghc/ghc/issues/14771
# Environment
* GHC version used: 8.4.4, 8.6.5# Summary
Using TypeError seems to hide other type error messages due to eg, bad arguments passed to a function.
# Steps to reproduce
Load into ghci:
```
{# LANGUAGE DataKinds, UndecidableInstances, TypeFamilies #}
import GHC.TypeLits
type family Check x :: Bool where
Check 'True = 'True
Check x = 'False
foo :: Check 'False ~ 'True => Int > String
foo n = "never reached"
type family Check2 x :: Bool where
Check2 'True = 'True
Check2 x = TypeError ('Text "no")
foo2 :: Check2 'False ~ 'True => Int > String
foo2 n = "never reached"
```
```
ghci> foo "bar"
<interactive>:69:1: error:
• Couldn't match type ‘'False’ with ‘'True’
arising from a use of ‘foo’
• In the expression: foo "bar"
In an equation for ‘it’: it = foo "bar"
<interactive>:69:5: error:
• Couldn't match expected type ‘Int’ with actual type ‘[Char]’
• In the first argument of ‘foo’, namely ‘"bar"’
In the expression: foo "bar"
In an equation for ‘it’: it = foo "bar"
ghci> foo2 "bar"
<interactive>:70:1: error:
• no
• In the expression: foo2 "bar"
In an equation for ‘it’: it = foo2 "bar"
```
# Expected behavior
I expected to see the same error about Int vs [Char] for foo2 as is shown for foo, as well as the custom TypeError. However, the use of TypeError somehow prevents the Int vs [Char] error from being displayed.
This is preventing me from using TypeError in situations where there might be another, more basic
type error in the same code.
This may be related to https://gitlab.haskell.org/ghc/ghc/issues/14771
# Environment
* GHC version used: 8.4.4, 8.6.5https://gitlab.haskell.org/ghc/ghc//issues/16946"No skolem info"20190726T13:49:54Zcactus"No skolem info"On GHC 8.6.3, I am trying to typecheck the following code:
```
{# LANGUAGE RankNTypes, TypeFamilies, PolyKinds, FunctionalDependencies #}
import Data.Kind
class CatMonad (c :: k > k > Type) (m :: forall (x :: k) (y :: k). c x y > Type > Type)  c > m where
type Id c :: c x x
xpure :: a > m (Id c) a
boom :: forall (c :: k > k > Type) (m :: forall (x :: k) (y :: k). c x y > Type > Type) a. CatMonad c m => a > m (Id c) a
boom = xpure
```
GHC panics with the following error message:
> ```
> error:ghc: panic! (the 'impossible' happened)
> (GHC version 8.6.3 for x86_64unknownlinux):
> No skolem info:
> [k_a2vT[sk:0]]
> Call stack:
> CallStack (from HasCallStack):
> callStackDoc, called at compiler/utils/Outputable.hs:1160:37 in ghc:Outputable
> pprPanic, called at compiler/typecheck/TcErrors.hs:2891:5 in ghc:TcErrors
>
> Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug
>
> ```
>
If you're thinking, "oh my god, why would you write code like that?!?!?!", the background is [this Stack Overflow answer](https://stackoverflow.com/a/57046042/477476), and specifically, pining for overriding `return` and `(>>=)` using `RebindableSyntax` to be able to use `do`notation with (category)indexed monads.On GHC 8.6.3, I am trying to typecheck the following code:
```
{# LANGUAGE RankNTypes, TypeFamilies, PolyKinds, FunctionalDependencies #}
import Data.Kind
class CatMonad (c :: k > k > Type) (m :: forall (x :: k) (y :: k). c x y > Type > Type)  c > m where
type Id c :: c x x
xpure :: a > m (Id c) a
boom :: forall (c :: k > k > Type) (m :: forall (x :: k) (y :: k). c x y > Type > Type) a. CatMonad c m => a > m (Id c) a
boom = xpure
```
GHC panics with the following error message:
> ```
> error:ghc: panic! (the 'impossible' happened)
> (GHC version 8.6.3 for x86_64unknownlinux):
> No skolem info:
> [k_a2vT[sk:0]]
> Call stack:
> CallStack (from HasCallStack):
> callStackDoc, called at compiler/utils/Outputable.hs:1160:37 in ghc:Outputable
> pprPanic, called at compiler/typecheck/TcErrors.hs:2891:5 in ghc:TcErrors
>
> Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug
>
> ```
>
If you're thinking, "oh my god, why would you write code like that?!?!?!", the background is [this Stack Overflow answer](https://stackoverflow.com/a/57046042/477476), and specifically, pining for overriding `return` and `(>>=)` using `RebindableSyntax` to be able to use `do`notation with (category)indexed monads.https://gitlab.haskell.org/ghc/ghc//issues/16947Refactor Ct and friends20210122T23:50:33ZRichard Eisenbergrae@richarde.devRefactor Ct and friendsRight now, the `Ct` type contains many constructors. This ticket tracks breaking up this type into smaller ones. Candidates:
* All constraints are born as noncanonical. So the bag of constraints in the `TcM` monad are all noncanonical. This should be its own type.
* Equality constraints are dealt with separately from others. (See details on the description of the inert set.) These should be their own types, too.
* A work list has both canonical and noncanonical constraints. But this might be the only place we need the full sum.Right now, the `Ct` type contains many constructors. This ticket tracks breaking up this type into smaller ones. Candidates:
* All constraints are born as noncanonical. So the bag of constraints in the `TcM` monad are all noncanonical. This should be its own type.
* Equality constraints are dealt with separately from others. (See details on the description of the inert set.) These should be their own types, too.
* A work list has both canonical and noncanonical constraints. But this might be the only place we need the full sum.9.2.1Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://gitlab.haskell.org/ghc/ghc//issues/16954Type error being deferred to other values20200123T19:40:41ZSome GuyType error being deferred to other values## Summary
The following code doesn't type check because of the last line `<> radius`, which has type `Double` while the rest of the values have type `Diagram B`.
```
{# LANGUAGE NoMonomorphismRestriction #}
{# LANGUAGE TypeFamilies #}
module Test where
import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
someFunc :: Double > Diagram B
someFunc radius = result
where
commonSubExpr = circle radius
unrelatedValue
= commonSubExpr
<> (circle 5 :: Diagram B)
result
= commonSubExpr
<> (circle 1 :: Diagram B)
<> radius
```
However, GHC prints out type errors on almost every value but the radius:
```
...\Test.hs:9:19: error:
* Couldn't match type `Double' with `QDiagram B (V B) (N B) Any'
Expected type: Diagram B
Actual type: Double
* In the expression: result
In an equation for `someFunc':
someFunc radius
= result
where
commonSubExpr = circle radius
unrelatedValue = commonSubExpr <> (circle 5 :: Diagram B)
result = commonSubExpr <> (circle 1 :: Diagram B) <> radius

9  someFunc radius = result
 ^^^^^^
...\Test.hs:15:16: error:
* Couldn't match type `QDiagram B (V B) (N B) Any' with `Double'
Expected type: Double
Actual type: Diagram B
* In the second argument of `(<>)', namely
`(circle 5 :: Diagram B)'
In the expression: commonSubExpr <> (circle 5 :: Diagram B)
In an equation for `unrelatedValue':
unrelatedValue = commonSubExpr <> (circle 5 :: Diagram B)

15  <> (circle 5 :: Diagram B)
 ^^^^^^^^^^^^^^^^^^^^^
...\Test.hs:19:17: error:
* Couldn't match type `QDiagram B (V B) (N B) Any' with `Double'
Expected type: Double
Actual type: Diagram B
* In the first argument of `(<>)', namely `(circle 1 :: Diagram B)'
In the second argument of `(<>)', namely
`(circle 1 :: Diagram B) <> radius'
In the expression:
commonSubExpr <> (circle 1 :: Diagram B) <> radius

19  <> (circle 1 :: Diagram B)
 ^^^^^^^^^^^^^^^^^^^^^
```
where `QDiagram B (V B) (N B) Any` is what `Diagram B` resolves to.
There is a lot of odd with this. For one, GHC seems convinced that the type of `result` is `Double` even though `Double` doesn't even have a `Semigroup` instance. Secondly, the type error seems to spread through `commonSubExpr` into `unrelatedValue`. Additionally `circle x` returns a value from a typeclass called `TrailLike`, but the typeclass doesn't have an instance for `Double`, so it's a bit odd that GHC doesn't have a problem with the type of `commonSubExpr`.
Also, if you replace the definition of `commonSubExpr` with `commonSubExpr = circle (1.2 :: Double)`, GHC will stop reporting the second type error even though the types of all expresions should be the same.
## Steps to reproduce
Compile the above code along with the diagramslib, diagrams and diagramssvg libraries.
## Expected behavior
I expected GHC to give an error about the right and left arguments of the last `<>` being different, thus pointing directly to the source of the type error.
## Environment
* GHC version used: 8.6.5
* Diagrams version used: 1.4 (for all 3 libraries)
Optional:
* Operating System: Windows 10
* System Architecture: x8664## Summary
The following code doesn't type check because of the last line `<> radius`, which has type `Double` while the rest of the values have type `Diagram B`.
```
{# LANGUAGE NoMonomorphismRestriction #}
{# LANGUAGE TypeFamilies #}
module Test where
import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
someFunc :: Double > Diagram B
someFunc radius = result
where
commonSubExpr = circle radius
unrelatedValue
= commonSubExpr
<> (circle 5 :: Diagram B)
result
= commonSubExpr
<> (circle 1 :: Diagram B)
<> radius
```
However, GHC prints out type errors on almost every value but the radius:
```
...\Test.hs:9:19: error:
* Couldn't match type `Double' with `QDiagram B (V B) (N B) Any'
Expected type: Diagram B
Actual type: Double
* In the expression: result
In an equation for `someFunc':
someFunc radius
= result
where
commonSubExpr = circle radius
unrelatedValue = commonSubExpr <> (circle 5 :: Diagram B)
result = commonSubExpr <> (circle 1 :: Diagram B) <> radius

9  someFunc radius = result
 ^^^^^^
...\Test.hs:15:16: error:
* Couldn't match type `QDiagram B (V B) (N B) Any' with `Double'
Expected type: Double
Actual type: Diagram B
* In the second argument of `(<>)', namely
`(circle 5 :: Diagram B)'
In the expression: commonSubExpr <> (circle 5 :: Diagram B)
In an equation for `unrelatedValue':
unrelatedValue = commonSubExpr <> (circle 5 :: Diagram B)

15  <> (circle 5 :: Diagram B)
 ^^^^^^^^^^^^^^^^^^^^^
...\Test.hs:19:17: error:
* Couldn't match type `QDiagram B (V B) (N B) Any' with `Double'
Expected type: Double
Actual type: Diagram B
* In the first argument of `(<>)', namely `(circle 1 :: Diagram B)'
In the second argument of `(<>)', namely
`(circle 1 :: Diagram B) <> radius'
In the expression:
commonSubExpr <> (circle 1 :: Diagram B) <> radius

19  <> (circle 1 :: Diagram B)
 ^^^^^^^^^^^^^^^^^^^^^
```
where `QDiagram B (V B) (N B) Any` is what `Diagram B` resolves to.
There is a lot of odd with this. For one, GHC seems convinced that the type of `result` is `Double` even though `Double` doesn't even have a `Semigroup` instance. Secondly, the type error seems to spread through `commonSubExpr` into `unrelatedValue`. Additionally `circle x` returns a value from a typeclass called `TrailLike`, but the typeclass doesn't have an instance for `Double`, so it's a bit odd that GHC doesn't have a problem with the type of `commonSubExpr`.
Also, if you replace the definition of `commonSubExpr` with `commonSubExpr = circle (1.2 :: Double)`, GHC will stop reporting the second type error even though the types of all expresions should be the same.
## Steps to reproduce
Compile the above code along with the diagramslib, diagrams and diagramssvg libraries.
## Expected behavior
I expected GHC to give an error about the right and left arguments of the last `<>` being different, thus pointing directly to the source of the type error.
## Environment
* GHC version used: 8.6.5
* Diagrams version used: 1.4 (for all 3 libraries)
Optional:
* Operating System: Windows 10
* System Architecture: x8664https://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/17024Poor interaction between functional dependencies and partial type signatures20200312T13:58:57ZDavid FeuerPoor interaction between functional dependencies and partial type signatures## Summary
A fundep is surprisingly unable to fill in a partial type signature
## Steps to reproduce
```haskell
{# language TypeFamilies, FunctionalDependencies, GADTs, DataKinds, TypeOperators, ScopedTypeVariables, FlexibleInstances , UndecidableInstances, PartialTypeSignatures #}
infixr 6 :::
data HList xs where
HNil :: HList '[]
(:::) :: a > HList as > HList (a ': as)
class AppHList ts o f  ts f > o, ts o > f where
appHList :: f > HList ts > o
instance AppHList '[] o o where
appHList x HNil = x
instance AppHList ts o f => AppHList (t : ts) o (t > f) where
appHList f (x ::: xs) = appHList (f x) xs
foo :: (a > b > c) > HList '[a, b] > _
foo = appHList
```
This fails with
```
AbstractList.hs:35:7: error:
• Couldn't match type ‘c’ with ‘w0’
arising from a functional dependency between:
constraint ‘AppHList '[] w0 c’ arising from a use of ‘appHList’
instance ‘AppHList '[] o o’ at AbstractList.hs:29:1025
‘c’ is a rigid type variable bound by
the inferred type of foo :: (a > b > c) > HList '[a, b] > w0
at AbstractList.hs:35:114
• In the expression: appHList
In an equation for ‘foo’: foo = appHList
• Relevant bindings include
foo :: (a > b > c) > HList '[a, b] > w0
(bound at AbstractList.hs:35:1)
```
## Expected behavior
I'd expect GHC to fill in `_` with `c`. Indeed, if I leave out the type signature and write
```haskell
foo (f :: a > b > c) (args :: HList '[a, b]) = appHList f args
```
then GHC correctly infers `foo :: (a > b > c) > HList '[a, b] > c`.
## Environment
* GHC version used: 8.6.3
Optional:
* Operating System:
* System Architecture:## Summary
A fundep is surprisingly unable to fill in a partial type signature
## Steps to reproduce
```haskell
{# language TypeFamilies, FunctionalDependencies, GADTs, DataKinds, TypeOperators, ScopedTypeVariables, FlexibleInstances , UndecidableInstances, PartialTypeSignatures #}
infixr 6 :::
data HList xs where
HNil :: HList '[]
(:::) :: a > HList as > HList (a ': as)
class AppHList ts o f  ts f > o, ts o > f where
appHList :: f > HList ts > o
instance AppHList '[] o o where
appHList x HNil = x
instance AppHList ts o f => AppHList (t : ts) o (t > f) where
appHList f (x ::: xs) = appHList (f x) xs
foo :: (a > b > c) > HList '[a, b] > _
foo = appHList
```
This fails with
```
AbstractList.hs:35:7: error:
• Couldn't match type ‘c’ with ‘w0’
arising from a functional dependency between:
constraint ‘AppHList '[] w0 c’ arising from a use of ‘appHList’
instance ‘AppHList '[] o o’ at AbstractList.hs:29:1025
‘c’ is a rigid type variable bound by
the inferred type of foo :: (a > b > c) > HList '[a, b] > w0
at AbstractList.hs:35:114
• In the expression: appHList
In an equation for ‘foo’: foo = appHList
• Relevant bindings include
foo :: (a > b > c) > HList '[a, b] > w0
(bound at AbstractList.hs:35:1)
```
## Expected behavior
I'd expect GHC to fill in `_` with `c`. Indeed, if I leave out the type signature and write
```haskell
foo (f :: a > b > c) (args :: HList '[a, b]) = appHList f args
```
then GHC correctly infers `foo :: (a > b > c) > HList '[a, b] > c`.
## Environment
* GHC version used: 8.6.3
Optional:
* Operating System:
* System Architecture: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/17060Compiler ignores Typeable constraint20191008T09:44:26ZRobert PeszekCompiler ignores Typeable constraint## Summary
Compiler allows passing types with no `Typeable` instance to functions declared with `Typeable` constraint.
## Steps to reproduce
The following compiles (no pragmas needed)
```haskell
import Data.Typeable
brokenGhc :: Typeable a => a > a
brokenGhc = id
tst = brokenGhc (Foo "bar")
brokenGhc2 :: (Typeable a) => a > String
brokenGhc2 = show . typeOf
tst2 = brokenGhc2 (Foo "Bar")
 ghci> tst2
 "Foo"
data Foo = Foo String
```
Possibly related to #10770?
## Expected behavior
`tst` and `tst2` should not compile. Note `Foo` has no instances!
## Environment
* GHC version used:
Tested with ghc8.6.5/lts14.0, ghc8.2.2/lts12.22
Optional:
* Operating System:
Ubuntu 18.04 and Ubuntu 18.10
* System Architecture:
## Suggested Labels:
~Typeable
~bug
~"program incorrectly accepted"## Summary
Compiler allows passing types with no `Typeable` instance to functions declared with `Typeable` constraint.
## Steps to reproduce
The following compiles (no pragmas needed)
```haskell
import Data.Typeable
brokenGhc :: Typeable a => a > a
brokenGhc = id
tst = brokenGhc (Foo "bar")
brokenGhc2 :: (Typeable a) => a > String
brokenGhc2 = show . typeOf
tst2 = brokenGhc2 (Foo "Bar")
 ghci> tst2
 "Foo"
data Foo = Foo String
```
Possibly related to #10770?
## Expected behavior
`tst` and `tst2` should not compile. Note `Foo` has no instances!
## Environment
* GHC version used:
Tested with ghc8.6.5/lts14.0, ghc8.2.2/lts12.22
Optional:
* Operating System:
Ubuntu 18.04 and Ubuntu 18.10
* System Architecture:
## Suggested Labels:
~Typeable
~bug
~"program incorrectly accepted"8.10.1https://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/17077"Quantification by level numbers would fail" for an illkinded signature20190924T16:49:34ZVladislav Zavialov"Quantification by level numbers would fail" for an illkinded signature## Summary
With assertions enabled, this program causes a warning about level numbers:
```haskell
{# LANGUAGE RankNTypes, PolyKinds #}
{# OPTIONS_GHC fprintexplicitkinds #}
module T where
import Data.Proxy
t :: Proxy (z :: forall k. a)
t = t
```
The warning and the kind error are as follows:
```
WARNING: file compiler/typecheck/TcMType.hs, line 1472
Quantification by level numbers would fail
Outer level = 0
dep_tkvs = {k_a1f6[tau:0], k_a1f7[tau:0], a_a1eI[sk:1],
k_a1f4[tau:1]}
co_vars = co_a1f3 :: k_a1eK[tau:1]
~# (forall (k :: k_a1eX[tau:1]). a_a1eI[sk:1])
co_tvs = {a_a1eI[sk:1], k_a1eK[tau:1], k_a1eX[tau:1], co_a1f3}
dep_kvs = [k_a1f4[tau:1]]
dep_kvs2 = [a_a1eI[sk:1], k_a1f4[tau:1]]
nondep_tvs = []
nondep_tvs2 = []
Call stack:
CallStack (from HasCallStack):
callStackDoc, called at compiler/utils/Outputable.hs:1237:29 in ghc:Outputable
warnPprTrace, called at compiler/typecheck/TcMType.hs:1472:11 in ghc:TcMType
Bug.hs:7:13: error:
• Expected kind ‘forall (k :: k1). a’, but ‘z’ has kind ‘k0’
• In the first argument of ‘Proxy’, namely ‘(z :: forall k. a)’
In the type signature: t :: Proxy (z :: forall k. a)

7  t :: Proxy (z :: forall k. a)

```
## Steps to reproduce
1. Compile GHC with assertions enabled (`hadrian/build.sh j flavour=Devel2`).
2. Load the aforementioned program in GHCi (`_build/stage1/bin/ghc interactive`)
## Expected behavior
No warning.
## Environment
* GHC version used: HEAD## Summary
With assertions enabled, this program causes a warning about level numbers:
```haskell
{# LANGUAGE RankNTypes, PolyKinds #}
{# OPTIONS_GHC fprintexplicitkinds #}
module T where
import Data.Proxy
t :: Proxy (z :: forall k. a)
t = t
```
The warning and the kind error are as follows:
```
WARNING: file compiler/typecheck/TcMType.hs, line 1472
Quantification by level numbers would fail
Outer level = 0
dep_tkvs = {k_a1f6[tau:0], k_a1f7[tau:0], a_a1eI[sk:1],
k_a1f4[tau:1]}
co_vars = co_a1f3 :: k_a1eK[tau:1]
~# (forall (k :: k_a1eX[tau:1]). a_a1eI[sk:1])
co_tvs = {a_a1eI[sk:1], k_a1eK[tau:1], k_a1eX[tau:1], co_a1f3}
dep_kvs = [k_a1f4[tau:1]]
dep_kvs2 = [a_a1eI[sk:1], k_a1f4[tau:1]]
nondep_tvs = []
nondep_tvs2 = []
Call stack:
CallStack (from HasCallStack):
callStackDoc, called at compiler/utils/Outputable.hs:1237:29 in ghc:Outputable
warnPprTrace, called at compiler/typecheck/TcMType.hs:1472:11 in ghc:TcMType
Bug.hs:7:13: error:
• Expected kind ‘forall (k :: k1). a’, but ‘z’ has kind ‘k0’
• In the first argument of ‘Proxy’, namely ‘(z :: forall k. a)’
In the type signature: t :: Proxy (z :: forall k. a)

7  t :: Proxy (z :: forall k. a)

```
## Steps to reproduce
1. Compile GHC with assertions enabled (`hadrian/build.sh j flavour=Devel2`).
2. Load the aforementioned program in GHCi (`_build/stage1/bin/ghc interactive`)
## Expected behavior
No warning.
## Environment
* GHC version used: HEAD8.10.1Simon Peyton JonesRichard Eisenbergrae@richarde.devSimon Peyton Joneshttps://gitlab.haskell.org/ghc/ghc//issues/17105GHC unexpectedly reports variable as untouchable and suggests XAmbiguousType...20190902T10:36:05ZSergey VinokurovGHC unexpectedly reports variable as untouchable and suggests XAmbiguousTypes after enabling constraints via associated type family under rank2 argumentSorry for long subject, couldn't express it in a more succinct way :)
Please consider the following program. I have defined function `hzygo` without any issues, but after slight generalisation GHC doesn't accept `hzygo1` any more. Please see the error message below the program. However, slightly more general `hzygo2` is accepted.
```haskell
{# LANGUAGE ConstraintKinds #}
{# LANGUAGE DataKinds #}
{# LANGUAGE GADTs #}
{# LANGUAGE KindSignatures #}
{# LANGUAGE NoStarIsType #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE RankNTypes #}
{# LANGUAGE ScopedTypeVariables #}
{# LANGUAGE TypeFamilies #}
module Main (main) where
import Data.Kind
import Data.Functor.Product
hfst :: Product a b ix > a ix
hfst (Pair a _) = a
hsnd :: Product a b ix > b ix
hsnd (Pair _ b) = b
newtype HFix (f :: (k > Type) > (k > Type)) (ix :: k) =
HFix { unHFix :: f (HFix f) ix }
class HFunctor (f :: (k > Type) > (k > Type)) where
hmap :: (forall ix. a ix > b ix) > (forall ix. f a ix > f b ix)
hcata
:: forall f a.
HFunctor f
=> (forall ix. f a ix > a ix)
> (forall ix. HFix f ix > a ix)
hcata alg = go
where
go :: forall ix. HFix f ix > a ix
go = alg . hmap go . unHFix
hzygo
:: forall f a b.
HFunctor f
=> (forall ix. f (Product a b) ix > a ix)
> (forall ix. f b ix > b ix)
> (forall ix. HFix f ix > a ix)
hzygo alga algb = hfst . hcata alg
where
alg :: f (Product a b) ix > Product a b ix
alg x = Pair (alga x) (algb $ hmap hsnd x)
class Constrained (f :: (k1 > k2) > (k1 > k2)) where
type Constraints f :: k1 > Constraint
class Constrained f => HFunctor' (f :: (k > Type) > (k > Type)) where
hmap'
:: (forall ix. Constraints f ix => a ix > b ix)
> (forall ix. Constraints f ix => f a ix > f b ix)
hcata'
:: forall f a.
HFunctor' f
=> (forall ix. Constraints f ix => f a ix > a ix)
> (forall ix. Constraints f ix => HFix f ix > a ix)
hcata' alg = go
where
go :: forall ix. Constraints f ix => HFix f ix > a ix
go = alg . hmap' go . unHFix
hzygo2
:: forall f a b.
HFunctor' f
=> (forall ix. Constraints f ix => f (Product a b) ix > a ix)
> (forall ix. Constraints f ix => f b ix > b ix)
> (forall ix. Constraints f ix => HFix f ix > Product a b ix)
hzygo2 alga algb = hcata' alg
where
alg :: Constraints f ix => f (Product a b) ix > Product a b ix
alg x = Pair (alga x) (algb $ hmap' hsnd x)
hzygo1
:: forall f a b.
HFunctor' f
=> (forall ix. Constraints f ix => f (Product a b) ix > a ix)
> (forall ix. Constraints f ix => f b ix > b ix)
> (forall ix. Constraints f ix => HFix f ix > a ix)
hzygo1 alga algb = hfst . hcata' alg
where
alg :: Constraints f ix => f (Product a b) ix > Product a b ix
alg x = Pair (alga x) (algb $ hmap' hsnd x)
main :: IO ()
main =
pure ()
```
```
$ ghc version
The Glorious Glasgow Haskell Compilation System, version 8.6.5
$ ghc c Main.hs
Main.hs:77:6: error:
• Couldn't match type ‘b0’ with ‘b’
‘b0’ is untouchable
inside the constraints: Constraints f ix1
bound by the type signature for:
hzygo' :: forall (ix1 :: k1).
Constraints f ix1 =>
f b0 ix1 > b0 ix1
at Main.hs:(77,6)(81,64)
‘b’ is a rigid type variable bound by
the type signature for:
hzygo' :: forall k1 (f :: (k1 > *) > k1 > *) (a :: k1
> *) (b :: k1 > *).
HFunctor f =>
(forall (ix1 :: k1).
Constraints f ix1 =>
f (Product a b) ix1 > a ix1)
> (forall (ix1 :: k1). Constraints f ix1 => f b ix1 > b ix1)
> forall (ix :: k1). Constraints f ix => HFix f ix > a ix
at Main.hs:(77,6)(81,64)
Expected type: f b0 ix1 > b0 ix1
Actual type: f b ix1 > b ix1
• In the ambiguity check for ‘hzygo'’
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
In the type signature:
hzygo' :: forall f a b.
HFunctor f =>
(forall ix. Constraints f ix => f (Product a b) ix > a ix)
> (forall ix. Constraints f ix => f b ix > b ix)
> (forall ix. Constraints f ix => HFix f ix > a ix)

77  :: forall f a b.
 ^^^^^^^^^^^^^...
Main.hs:77:6: error:
• Couldn't match type ‘b0’ with ‘b’
‘b0’ is untouchable
inside the constraints: Constraints f ix1
bound by the type signature for:
hzygo' :: forall (ix1 :: k1).
Constraints f ix1 =>
f (Product a b0) ix1 > a ix1
at Main.hs:(77,6)(81,64)
‘b’ is a rigid type variable bound by
the type signature for:
hzygo' :: forall k1 (f :: (k1 > *) > k1 > *) (a :: k1
> *) (b :: k1 > *).
HFunctor f =>
(forall (ix1 :: k1).
Constraints f ix1 =>
f (Product a b) ix1 > a ix1)
> (forall (ix1 :: k1). Constraints f ix1 => f b ix1 > b ix1)
> forall (ix :: k1). Constraints f ix => HFix f ix > a ix
at Main.hs:(77,6)(81,64)
Expected type: f (Product a b0) ix1 > a ix1
Actual type: f (Product a b) ix1 > a ix1
• In the ambiguity check for ‘hzygo'’
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
In the type signature:
hzygo' :: forall f a b.
HFunctor f =>
(forall ix. Constraints f ix => f (Product a b) ix > a ix)
> (forall ix. Constraints f ix => f b ix > b ix)
> (forall ix. Constraints f ix => HFix f ix > a ix)

77  :: forall f a b.
 ^^^^^^^^^^^^^...
```Sorry for long subject, couldn't express it in a more succinct way :)
Please consider the following program. I have defined function `hzygo` without any issues, but after slight generalisation GHC doesn't accept `hzygo1` any more. Please see the error message below the program. However, slightly more general `hzygo2` is accepted.
```haskell
{# LANGUAGE ConstraintKinds #}
{# LANGUAGE DataKinds #}
{# LANGUAGE GADTs #}
{# LANGUAGE KindSignatures #}
{# LANGUAGE NoStarIsType #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE RankNTypes #}
{# LANGUAGE ScopedTypeVariables #}
{# LANGUAGE TypeFamilies #}
module Main (main) where
import Data.Kind
import Data.Functor.Product
hfst :: Product a b ix > a ix
hfst (Pair a _) = a
hsnd :: Product a b ix > b ix
hsnd (Pair _ b) = b
newtype HFix (f :: (k > Type) > (k > Type)) (ix :: k) =
HFix { unHFix :: f (HFix f) ix }
class HFunctor (f :: (k > Type) > (k > Type)) where
hmap :: (forall ix. a ix > b ix) > (forall ix. f a ix > f b ix)
hcata
:: forall f a.
HFunctor f
=> (forall ix. f a ix > a ix)
> (forall ix. HFix f ix > a ix)
hcata alg = go
where
go :: forall ix. HFix f ix > a ix
go = alg . hmap go . unHFix
hzygo
:: forall f a b.
HFunctor f
=> (forall ix. f (Product a b) ix > a ix)
> (forall ix. f b ix > b ix)
> (forall ix. HFix f ix > a ix)
hzygo alga algb = hfst . hcata alg
where
alg :: f (Product a b) ix > Product a b ix
alg x = Pair (alga x) (algb $ hmap hsnd x)
class Constrained (f :: (k1 > k2) > (k1 > k2)) where
type Constraints f :: k1 > Constraint
class Constrained f => HFunctor' (f :: (k > Type) > (k > Type)) where
hmap'
:: (forall ix. Constraints f ix => a ix > b ix)
> (forall ix. Constraints f ix => f a ix > f b ix)
hcata'
:: forall f a.
HFunctor' f
=> (forall ix. Constraints f ix => f a ix > a ix)
> (forall ix. Constraints f ix => HFix f ix > a ix)
hcata' alg = go
where
go :: forall ix. Constraints f ix => HFix f ix > a ix
go = alg . hmap' go . unHFix
hzygo2
:: forall f a b.
HFunctor' f
=> (forall ix. Constraints f ix => f (Product a b) ix > a ix)
> (forall ix. Constraints f ix => f b ix > b ix)
> (forall ix. Constraints f ix => HFix f ix > Product a b ix)
hzygo2 alga algb = hcata' alg
where
alg :: Constraints f ix => f (Product a b) ix > Product a b ix
alg x = Pair (alga x) (algb $ hmap' hsnd x)
hzygo1
:: forall f a b.
HFunctor' f
=> (forall ix. Constraints f ix => f (Product a b) ix > a ix)
> (forall ix. Constraints f ix => f b ix > b ix)
> (forall ix. Constraints f ix => HFix f ix > a ix)
hzygo1 alga algb = hfst . hcata' alg
where
alg :: Constraints f ix => f (Product a b) ix > Product a b ix
alg x = Pair (alga x) (algb $ hmap' hsnd x)
main :: IO ()
main =
pure ()
```
```
$ ghc version
The Glorious Glasgow Haskell Compilation System, version 8.6.5
$ ghc c Main.hs
Main.hs:77:6: error:
• Couldn't match type ‘b0’ with ‘b’
‘b0’ is untouchable
inside the constraints: Constraints f ix1
bound by the type signature for:
hzygo' :: forall (ix1 :: k1).
Constraints f ix1 =>
f b0 ix1 > b0 ix1
at Main.hs:(77,6)(81,64)
‘b’ is a rigid type variable bound by
the type signature for:
hzygo' :: forall k1 (f :: (k1 > *) > k1 > *) (a :: k1
> *) (b :: k1 > *).
HFunctor f =>
(forall (ix1 :: k1).
Constraints f ix1 =>
f (Product a b) ix1 > a ix1)
> (forall (ix1 :: k1). Constraints f ix1 => f b ix1 > b ix1)
> forall (ix :: k1). Constraints f ix => HFix f ix > a ix
at Main.hs:(77,6)(81,64)
Expected type: f b0 ix1 > b0 ix1
Actual type: f b ix1 > b ix1
• In the ambiguity check for ‘hzygo'’
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
In the type signature:
hzygo' :: forall f a b.
HFunctor f =>
(forall ix. Constraints f ix => f (Product a b) ix > a ix)
> (forall ix. Constraints f ix => f b ix > b ix)
> (forall ix. Constraints f ix => HFix f ix > a ix)

77  :: forall f a b.
 ^^^^^^^^^^^^^...
Main.hs:77:6: error:
• Couldn't match type ‘b0’ with ‘b’
‘b0’ is untouchable
inside the constraints: Constraints f ix1
bound by the type signature for:
hzygo' :: forall (ix1 :: k1).
Constraints f ix1 =>
f (Product a b0) ix1 > a ix1
at Main.hs:(77,6)(81,64)
‘b’ is a rigid type variable bound by
the type signature for:
hzygo' :: forall k1 (f :: (k1 > *) > k1 > *) (a :: k1
> *) (b :: k1 > *).
HFunctor f =>
(forall (ix1 :: k1).
Constraints f ix1 =>
f (Product a b) ix1 > a ix1)
> (forall (ix1 :: k1). Constraints f ix1 => f b ix1 > b ix1)
> forall (ix :: k1). Constraints f ix => HFix f ix > a ix
at Main.hs:(77,6)(81,64)
Expected type: f (Product a b0) ix1 > a ix1
Actual type: f (Product a b) ix1 > a ix1
• In the ambiguity check for ‘hzygo'’
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
In the type signature:
hzygo' :: forall f a b.
HFunctor f =>
(forall ix. Constraints f ix => f (Product a b) ix > a ix)
> (forall ix. Constraints f ix => f b ix > b ix)
> (forall ix. Constraints f ix => HFix f ix > a ix)

77  :: forall f a b.
 ^^^^^^^^^^^^^...
```https://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/17139Enormous error message when importing seemingly unused module20201226T13:07:15ZRyan ScottEnormous error message when importing seemingly unused module(Originally reported [here](https://github.com/goldfirere/singletons/issues/405).)
Here are two modules:
```hs
{# LANGUAGE DataKinds #}
{# LANGUAGE FlexibleInstances #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE RankNTypes #}
{# LANGUAGE TypeFamilyDependencies #}
{# LANGUAGE TypeOperators #}
 A strippeddown version of singletons
module A where
import Data.Kind (Type)
import Data.Proxy (Proxy)
data family Sing :: k > Type
class SingI a where
sing :: Sing a
class SingKind k where
type Demote k = (r :: Type)  r > k
toSing :: Demote k > Proxy k
data TyFun :: Type > Type > Type
type a ~> b = TyFun a b > Type
infixr 0 ~>
type family Apply (f :: k1 ~> k2) (x :: k1) :: k2
newtype instance Sing (f :: k1 ~> k2) =
SLambda { applySing :: forall t. Sing t > Sing (Apply f t) }
instance (SingKind k1, SingKind k2) => SingKind (k1 ~> k2) where
type Demote (k1 ~> k2) = Demote k1 > Demote k2
toSing = undefined
withSing :: SingI a => (Sing a > b) > b
withSing f = f sing
```
```hs
{# LANGUAGE GADTs #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE RankNTypes #}
{# LANGUAGE FlexibleInstances #}
{# LANGUAGE AllowAmbiguousTypes #}
module LongTypeError where
import A
type family TypeFam f fun where
TypeFam f (a > b) = f a > TypeFam f b
lift :: (a > b) > TypeFam f (a > b)
lift f = \x > _ (f <*> x)
```
If you try to run the following command using GHC 8.6.5, GHC 8.8.1, or HEAD:
```
$ /opt/ghc/8.6.5/bin/runghc LongTypeError.hs
```
You will be presented with one of the longest type errors in the history of type errors. The full thing is about 5,000 lines long, so here is an excerpt to give you a sense for how bad it is:
```
LongTypeError.hs:15:10: error:
• Couldn't match type ‘f’ with ‘(>) a’
‘f’ is a rigid type variable bound by
the type signature for:
lift :: forall a b (f :: * > *). (a > b) > TypeFam f (a > b)
at LongTypeError.hs:14:138
Expected type: TypeFam f (a > b)
Actual type: (a > a)
> (a > a)
> TypeFam
((>) a)
((a > a)
> (a > a > a)
> (a > a > a > a)
> Demote
((k1 ~> (k1 ~> (k1 ~> (k1 ~> k1))))
~> ((k1 ~> (k1 ~> (k1 ~> (k1 ~> (k1 ~> k1)))))
~> ((k1 ~> (k1 ~> (k1 ~> (k1 ~> (k1 ~> (k1 ~> k1))))))
~> ((k1
~> (k1 ~> (k1 ~> (k1 ~> (k1 ~> (k1 ~> (k1 ~> k1)))))))
~> ((k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1 ~> (k1 ~> (k1 ~> k1))))))))
~> ((k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> k1)))))))))
~> ((k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> k1))))))))))
~> ((k1
~> (k1
~> (k1
~> (k1
~> (k1
<elided>
~> k3)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
~> k4))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
Actual type: a > b
• In the first argument of ‘(<*>)’, namely ‘f’
In the first argument of ‘_’, namely ‘(f <*> x)’
In the expression: _ (f <*> x)
• Relevant bindings include
x :: a > a (bound at LongTypeError.hs:15:11)
f :: a > b (bound at LongTypeError.hs:15:6)
lift :: (a > b) > TypeFam f (a > b)
(bound at LongTypeError.hs:15:1)

15  lift f = \x > _ (f <*> x)
 ^
```
What is really curious about this example is that the `LongTypeError` module does not use anything from `A`. If you remove the `import A` line, you will instead get this much simpler error message:
```
LongTypeError.hs:15:10: error:
• Couldn't match type ‘f’ with ‘(>) a’
‘f’ is a rigid type variable bound by
the type signature for:
lift :: forall a b (f :: * > *). (a > b) > TypeFam f (a > b)
at LongTypeError.hs:14:138
Expected type: TypeFam f (a > b)
Actual type: (a > a)
> (a > a)
> TypeFam
((>) a) ((a > a) > (a > a > a) > (a > a > a > a) > t0)
• The lambda expression ‘\ x > _ (f <*> x)’ has one argument,
but its type ‘TypeFam f (a > b)’ has none
In the expression: \ x > _ (f <*> x)
In an equation for ‘lift’: lift f = \ x > _ (f <*> x)
• Relevant bindings include
f :: a > b (bound at LongTypeError.hs:15:6)
lift :: (a > b) > TypeFam f (a > b)
(bound at LongTypeError.hs:15:1)

15  lift f = \x > _ (f <*> x)
 ^^^^^^^^^^^^^^^^^
LongTypeError.hs:15:16: error:
• Found hole: _ :: (a > b0) > (a > a) > TypeFam ((>) a) b0
Where: ‘b0’ is an ambiguous type variable
‘a’ is a rigid type variable bound by
the type signature for:
lift :: forall a b (f :: * > *). (a > b) > TypeFam f (a > b)
at LongTypeError.hs:14:138
• In the expression: _
In the expression: _ (f <*> x)
The lambda expression ‘\ x > _ (f <*> x)’ has one argument,
but its type ‘TypeFam f (a > b)’ has none
• Relevant bindings include
x :: a > a (bound at LongTypeError.hs:15:11)
f :: a > b (bound at LongTypeError.hs:15:6)
lift :: (a > b) > TypeFam f (a > b)
(bound at LongTypeError.hs:15:1)

15  lift f = \x > _ (f <*> x)
 ^
LongTypeError.hs:15:19: error:
• Couldn't match type ‘b’ with ‘a > b0’
‘b’ is a rigid type variable bound by
the type signature for:
lift :: forall a b (f :: * > *). (a > b) > TypeFam f (a > b)
at LongTypeError.hs:14:138
Expected type: a
> a > (a > a) > (a > a > a) > (a > a > a > a) > t0
Actual type: a > b
• In the first argument of ‘(<*>)’, namely ‘f’
In the first argument of ‘_’, namely ‘(f <*> x)’
In the expression: _ (f <*> x)
• Relevant bindings include
x :: a > a (bound at LongTypeError.hs:15:11)
f :: a > b (bound at LongTypeError.hs:15:6)
lift :: (a > b) > TypeFam f (a > b)
(bound at LongTypeError.hs:15:1)

15  lift f = \x > _ (f <*> x)
 ^
```(Originally reported [here](https://github.com/goldfirere/singletons/issues/405).)
Here are two modules:
```hs
{# LANGUAGE DataKinds #}
{# LANGUAGE FlexibleInstances #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE RankNTypes #}
{# LANGUAGE TypeFamilyDependencies #}
{# LANGUAGE TypeOperators #}
 A strippeddown version of singletons
module A where
import Data.Kind (Type)
import Data.Proxy (Proxy)
data family Sing :: k > Type
class SingI a where
sing :: Sing a
class SingKind k where
type Demote k = (r :: Type)  r > k
toSing :: Demote k > Proxy k
data TyFun :: Type > Type > Type
type a ~> b = TyFun a b > Type
infixr 0 ~>
type family Apply (f :: k1 ~> k2) (x :: k1) :: k2
newtype instance Sing (f :: k1 ~> k2) =
SLambda { applySing :: forall t. Sing t > Sing (Apply f t) }
instance (SingKind k1, SingKind k2) => SingKind (k1 ~> k2) where
type Demote (k1 ~> k2) = Demote k1 > Demote k2
toSing = undefined
withSing :: SingI a => (Sing a > b) > b
withSing f = f sing
```
```hs
{# LANGUAGE GADTs #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE RankNTypes #}
{# LANGUAGE FlexibleInstances #}
{# LANGUAGE AllowAmbiguousTypes #}
module LongTypeError where
import A
type family TypeFam f fun where
TypeFam f (a > b) = f a > TypeFam f b
lift :: (a > b) > TypeFam f (a > b)
lift f = \x > _ (f <*> x)
```
If you try to run the following command using GHC 8.6.5, GHC 8.8.1, or HEAD:
```
$ /opt/ghc/8.6.5/bin/runghc LongTypeError.hs
```
You will be presented with one of the longest type errors in the history of type errors. The full thing is about 5,000 lines long, so here is an excerpt to give you a sense for how bad it is:
```
LongTypeError.hs:15:10: error:
• Couldn't match type ‘f’ with ‘(>) a’
‘f’ is a rigid type variable bound by
the type signature for:
lift :: forall a b (f :: * > *). (a > b) > TypeFam f (a > b)
at LongTypeError.hs:14:138
Expected type: TypeFam f (a > b)
Actual type: (a > a)
> (a > a)
> TypeFam
((>) a)
((a > a)
> (a > a > a)
> (a > a > a > a)
> Demote
((k1 ~> (k1 ~> (k1 ~> (k1 ~> k1))))
~> ((k1 ~> (k1 ~> (k1 ~> (k1 ~> (k1 ~> k1)))))
~> ((k1 ~> (k1 ~> (k1 ~> (k1 ~> (k1 ~> (k1 ~> k1))))))
~> ((k1
~> (k1 ~> (k1 ~> (k1 ~> (k1 ~> (k1 ~> (k1 ~> k1)))))))
~> ((k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1 ~> (k1 ~> (k1 ~> k1))))))))
~> ((k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> k1)))))))))
~> ((k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> (k1
~> k1))))))))))
~> ((k1
~> (k1
~> (k1
~> (k1
~> (k1
<elided>
~> k3)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
~> k4))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
Actual type: a > b
• In the first argument of ‘(<*>)’, namely ‘f’
In the first argument of ‘_’, namely ‘(f <*> x)’
In the expression: _ (f <*> x)
• Relevant bindings include
x :: a > a (bound at LongTypeError.hs:15:11)
f :: a > b (bound at LongTypeError.hs:15:6)
lift :: (a > b) > TypeFam f (a > b)
(bound at LongTypeError.hs:15:1)

15  lift f = \x > _ (f <*> x)
 ^
```
What is really curious about this example is that the `LongTypeError` module does not use anything from `A`. If you remove the `import A` line, you will instead get this much simpler error message:
```
LongTypeError.hs:15:10: error:
• Couldn't match type ‘f’ with ‘(>) a’
‘f’ is a rigid type variable bound by
the type signature for:
lift :: forall a b (f :: * > *). (a > b) > TypeFam f (a > b)
at LongTypeError.hs:14:138
Expected type: TypeFam f (a > b)
Actual type: (a > a)
> (a > a)
> TypeFam
((>) a) ((a > a) > (a > a > a) > (a > a > a > a) > t0)
• The lambda expression ‘\ x > _ (f <*> x)’ has one argument,
but its type ‘TypeFam f (a > b)’ has none
In the expression: \ x > _ (f <*> x)
In an equation for ‘lift’: lift f = \ x > _ (f <*> x)
• Relevant bindings include
f :: a > b (bound at LongTypeError.hs:15:6)
lift :: (a > b) > TypeFam f (a > b)
(bound at LongTypeError.hs:15:1)

15  lift f = \x > _ (f <*> x)
 ^^^^^^^^^^^^^^^^^
LongTypeError.hs:15:16: error:
• Found hole: _ :: (a > b0) > (a > a) > TypeFam ((>) a) b0
Where: ‘b0’ is an ambiguous type variable
‘a’ is a rigid type variable bound by
the type signature for:
lift :: forall a b (f :: * > *). (a > b) > TypeFam f (a > b)
at LongTypeError.hs:14:138
• In the expression: _
In the expression: _ (f <*> x)
The lambda expression ‘\ x > _ (f <*> x)’ has one argument,
but its type ‘TypeFam f (a > b)’ has none
• Relevant bindings include
x :: a > a (bound at LongTypeError.hs:15:11)
f :: a > b (bound at LongTypeError.hs:15:6)
lift :: (a > b) > TypeFam f (a > b)
(bound at LongTypeError.hs:15:1)

15  lift f = \x > _ (f <*> x)
 ^
LongTypeError.hs:15:19: error:
• Couldn't match type ‘b’ with ‘a > b0’
‘b’ is a rigid type variable bound by
the type signature for:
lift :: forall a b (f :: * > *). (a > b) > TypeFam f (a > b)
at LongTypeError.hs:14:138
Expected type: a
> a > (a > a) > (a > a > a) > (a > a > a > a) > t0
Actual type: a > b
• In the first argument of ‘(<*>)’, namely ‘f’
In the first argument of ‘_’, namely ‘(f <*> x)’
In the expression: _ (f <*> x)
• Relevant bindings include
x :: a > a (bound at LongTypeError.hs:15:11)
f :: a > b (bound at LongTypeError.hs:15:6)
lift :: (a > b) > TypeFam f (a > b)
(bound at LongTypeError.hs:15:1)

15  lift f = \x > _ (f <*> x)
 ^
```https://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 defaulting20210616T15:54:59ZKrzysztof 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/17202GHC does not use quantified constraint from transitive superclass20200319T18:05:13ZAlexis KingGHC does not use quantified constraint from transitive superclass## Summary
GHC sometimes does not choose to use a quantified constraint made available by a superclass, and I am not sure why. The program typechecks if a type annotation is added to give the instance search a hint. Here’s a small program that reproduces the issue:
```haskell
{# LANGUAGE ConstraintKinds #}
{# LANGUAGE GADTs #}
{# LANGUAGE QuantifiedConstraints #}
{# LANGUAGE TypeFamilies #}
module Sandbox where
type family F a
class C1 a
class (forall c. C1 c) => C2 a
class (forall b. (b ~ F a) => C2 a) => C3 a
data Dict c = c => Dict
foo :: forall a. C3 a => Dict (C1 a)
foo = Dict
bar :: forall a. C3 a => Dict (C1 a)
bar = Dict :: C2 a => Dict (C1 a)
```
The definition of `foo` is rejected with the following error:
```
error:
• Could not deduce (C1 a) arising from a use of ‘Dict’
from the context: C3 a
bound by the type signature for:
foo :: forall a. C3 a => Dict (C1 a)
Possible fix:
add (C1 a) to the context of
the type signature for:
foo :: forall a. C3 a => Dict (C1 a)
• In the expression: Dict
In an equation for ‘foo’: foo = Dict
```
However, `bar` is accepted, as GHC successfully solves the `C2 a` constraint using the quantified superclass of `C3`, then proceeds to use the quantified superclass of `C2` to solve `C1 a`.
What’s especially strange to me about this program is that the problem goes away if either constraint is nonquantified *or* if the type family is removed from the context of `C3`’s superclass. The second of those two conditions makes it sound like maybe this is related to #15347, but I don’t think it is. That issue is about equalities in quantified heads, while this involves an equality in a quantified instance context, and equalities in instance contexts are entirely legal.
I think `foo` should typecheck, but if it can’t for some reason I don’t understand, I’d prefer it at least fail with a more helpful error message.
## Environment
* GHC version used: 8.8.1## Summary
GHC sometimes does not choose to use a quantified constraint made available by a superclass, and I am not sure why. The program typechecks if a type annotation is added to give the instance search a hint. Here’s a small program that reproduces the issue:
```haskell
{# LANGUAGE ConstraintKinds #}
{# LANGUAGE GADTs #}
{# LANGUAGE QuantifiedConstraints #}
{# LANGUAGE TypeFamilies #}
module Sandbox where
type family F a
class C1 a
class (forall c. C1 c) => C2 a
class (forall b. (b ~ F a) => C2 a) => C3 a
data Dict c = c => Dict
foo :: forall a. C3 a => Dict (C1 a)
foo = Dict
bar :: forall a. C3 a => Dict (C1 a)
bar = Dict :: C2 a => Dict (C1 a)
```
The definition of `foo` is rejected with the following error:
```
error:
• Could not deduce (C1 a) arising from a use of ‘Dict’
from the context: C3 a
bound by the type signature for:
foo :: forall a. C3 a => Dict (C1 a)
Possible fix:
add (C1 a) to the context of
the type signature for:
foo :: forall a. C3 a => Dict (C1 a)
• In the expression: Dict
In an equation for ‘foo’: foo = Dict
```
However, `bar` is accepted, as GHC successfully solves the `C2 a` constraint using the quantified superclass of `C3`, then proceeds to use the quantified superclass of `C2` to solve `C1 a`.
What’s especially strange to me about this program is that the problem goes away if either constraint is nonquantified *or* if the type family is removed from the context of `C3`’s superclass. The second of those two conditions makes it sound like maybe this is related to #15347, but I don’t think it is. That issue is about equalities in quantified heads, while this involves an equality in a quantified instance context, and equalities in instance contexts are entirely legal.
I think `foo` should typecheck, but if it can’t for some reason I don’t understand, I’d prefer it at least fail with a more helpful error message.
## Environment
* GHC version used: 8.8.1https://gitlab.haskell.org/ghc/ghc//issues/17213Rankntypes without XRankNTypes20200714T17:14:18ZKrzysztof GogolewskiRankntypes without XRankNTypesConsider two modules:
```
{# LANGUAGE RankNTypes #}
module X where
foo :: (forall a. a > a) > Int
foo = foo
```
```
module Y where
import X
g = foo
```
Note that `Y` does not use `RankNTypes`.
Currently, `g` is accepted. However, the inferred type of `g` is `(forall a. a > a) > Int`, which cannot be written. We should not allow a value if writing its type requires an additional extension.
Reporting on behalf of Simon PJ.Consider two modules:
```
{# LANGUAGE RankNTypes #}
module X where
foo :: (forall a. a > a) > Int
foo = foo
```
```
module Y where
import X
g = foo
```
Note that `Y` does not use `RankNTypes`.
Currently, `g` is accepted. However, the inferred type of `g` is `(forall a. a > a) > Int`, which cannot be written. We should not allow a value if writing its type requires an additional extension.
Reporting on behalf of Simon PJ.8.10.1https://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/17301GHC.TypeLits.TypeError can print 'GHC.Types.Any' when existentials are involved20210111T13:10:21ZsheafGHC.TypeLits.TypeError can print 'GHC.Types.Any' when existentials are involvedI've run into a situation where GHC seems to forget some information.
Specifically: when wrapping typelevel information into a promoted existential datatype, and then unwrapping it, `Any` can appear.
I've boiled it down to the following simple example:
```haskell
{# LANGUAGE DataKinds #}
{# LANGUAGE GADTs #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE UndecidableInstances #}
module AnyTypeError where
import GHC.TypeLits
( TypeError, ErrorMessage(..) )
data A = MkA
data B (a :: A)
data TySing ty where
SB :: TySing (B a)
data ATySing where
MkATySing :: TySing ty > ATySing
type family Forget ty :: ATySing where
Forget (B a) = MkATySing SB
type family Message ty where
Message (MkATySing (_ :: TySing ty)) =
TypeError ( ShowType ty )
type KnownType = B MkA
foo :: Message (Forget KnownType) => ()
foo = ()
bar :: ()
bar = foo
```
```
AnyTypeError.hs:36:7: error:
* B GHC.Types.Any
* In the expression: foo
In an equation for `bar': bar = foo

36  bar = foo
 ^^^
Failed, no modules loaded.
```
I think the error message should instead be:
```
AnyTypeError.hs:36:7: error:
* B 'MkA
...
```
<p>
<details>
<summary> Show/hide background information (i.e. why this matters to me).</summary>
I ran into this code when working on giving helpful custom type errors. In a library I'm working on, the user can layout vertex data passed to the GPU by specifing interface slots (see e.g. [the OpenGL wiki](https://www.khronos.org/opengl/wiki/Layout_Qualifier_(GLSL)#Interface_components) for reference). For instance the following would be an invalid layout:
```haskell
type InvalidLayout = '[ Slot 0 0 ':> V 3 Double, Slot 1 0 ':> V 4 Float ]
```
After some lengthy typelevel computations with type families (involving existential types similar to those described above), I need to throw an error: the `V 4 Double` spills into the second slot (`Slot 1`) so overlaps with the `V 4 Float`. However the error message I end up throwing, because of the bug described here, comes out looking like this:
```
* Overlap at location 1, component 0:
 V GHC.Types.Any Double based at location 0, component 0,
 V GHC.Types.Any Float based at location 1, component 0.
```
The size of the vectors are lost, so the error message becomes confusingly vague.
</details>
</p>
I've tested this on GHC 8.6.5, 8.8.1 and HEAD (8.9.0.20190930), all giving identical results.I've run into a situation where GHC seems to forget some information.
Specifically: when wrapping typelevel information into a promoted existential datatype, and then unwrapping it, `Any` can appear.
I've boiled it down to the following simple example:
```haskell
{# LANGUAGE DataKinds #}
{# LANGUAGE GADTs #}
{# LANGUAGE PolyKinds #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE UndecidableInstances #}
module AnyTypeError where
import GHC.TypeLits
( TypeError, ErrorMessage(..) )
data A = MkA
data B (a :: A)
data TySing ty where
SB :: TySing (B a)
data ATySing where
MkATySing :: TySing ty > ATySing
type family Forget ty :: ATySing where
Forget (B a) = MkATySing SB
type family Message ty where
Message (MkATySing (_ :: TySing ty)) =
TypeError ( ShowType ty )
type KnownType = B MkA
foo :: Message (Forget KnownType) => ()
foo = ()
bar :: ()
bar = foo
```
```
AnyTypeError.hs:36:7: error:
* B GHC.Types.Any
* In the expression: foo
In an equation for `bar': bar = foo

36  bar = foo
 ^^^
Failed, no modules loaded.
```
I think the error message should instead be:
```
AnyTypeError.hs:36:7: error:
* B 'MkA
...
```
<p>
<details>
<summary> Show/hide background information (i.e. why this matters to me).</summary>
I ran into this code when working on giving helpful custom type errors. In a library I'm working on, the user can layout vertex data passed to the GPU by specifing interface slots (see e.g. [the OpenGL wiki](https://www.khronos.org/opengl/wiki/Layout_Qualifier_(GLSL)#Interface_components) for reference). For instance the following would be an invalid layout:
```haskell
type InvalidLayout = '[ Slot 0 0 ':> V 3 Double, Slot 1 0 ':> V 4 Float ]
```
After some lengthy typelevel computations with type families (involving existential types similar to those described above), I need to throw an error: the `V 4 Double` spills into the second slot (`Slot 1`) so overlaps with the `V 4 Float`. However the error message I end up throwing, because of the bug described here, comes out looking like this:
```
* Overlap at location 1, component 0:
 V GHC.Types.Any Double based at location 0, component 0,
 V GHC.Types.Any Float based at location 1, component 0.
```
The size of the vectors are lost, so the error message becomes confusingly vague.
</details>
</p>
I've tested this on GHC 8.6.5, 8.8.1 and HEAD (8.9.0.20190930), all giving identical results.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/17343BangPatterns in PatternGuards don't work like docs would suggest20191016T11:38:42ZJakob BrünkerBangPatterns in PatternGuards don't work like docs would suggest## Summary and Steps to reproduce
The docs don't seem to say anything special about the interaction between bang patterns and pattern guards, so I wouldn't expect them to work any differently there. And yet:
```haskell
let f = case undefined of !_ > () in f  (a) fails (as expected)
let f  let !_ = undefined = () in f  (b) fails (as expected)
let f  !_ < undefined = () in f  (c) succeeds...
```
## Expected behavior
I would expect `(c)` to fail, in the same way as `(a)` and `(b)` do.
Alternatively, an explanation for how BangPatterns interact with PatternGuards could be added to the "Bang patterns" section in `glasgow_exts.rst`.
## Environment
* GHC version used: 8.6.5, 8.8.1## Summary and Steps to reproduce
The docs don't seem to say anything special about the interaction between bang patterns and pattern guards, so I wouldn't expect them to work any differently there. And yet:
```haskell
let f = case undefined of !_ > () in f  (a) fails (as expected)
let f  let !_ = undefined = () in f  (b) fails (as expected)
let f  !_ < undefined = () in f  (c) succeeds...
```
## Expected behavior
I would expect `(c)` to fail, in the same way as `(a)` and `(b)` do.
Alternatively, an explanation for how BangPatterns interact with PatternGuards could be added to the "Bang patterns" section in `glasgow_exts.rst`.
## Environment
* GHC version used: 8.6.5, 8.8.18.10.1Sebastian GrafSebastian Grafhttps://gitlab.haskell.org/ghc/ghc//issues/17367Letbound wildcards are not letgeneralised20200205T23:07:07ZSebastian GrafLetbound wildcards are not letgeneralisedWith `XBangPatterns`, the act of declaring a letbinding without using it might have a sideeffect. Consider this example:
```haskell
{# LANGUAGE BangPatterns #}
f :: ()
f = let !x = undefined in ()
g :: ()
g = let !_ = undefined in ()
main = do
print f
print g
```
Both `f` and `g` declare a variable in a strict binding that is actually dead. Surprisingly, they lead to different code. Here's the Core (GHC 8.6.5) after optimisation:
```
main
= >>
(print
@ ()
GHC.Show.$fShow()
(case \ (@ a_a2hW) >
undefined
@ 'GHC.Types.LiftedRep
@ a_a2hW
(<snip>)
of
{ __DEFAULT >
GHC.Tuple.()
}))
(print
@ ()
GHC.Show.$fShow()
(case undefined
@ 'GHC.Types.LiftedRep
@ GHC.Types.Any
(<snip>)
of
{ __DEFAULT >
GHC.Tuple.()
}))
```
Note the `/\a. undefined @LiftedRep @a` in the first scrutinee. This is ultimately due to the fact that `x` is letgeneralised, whereas `_` is not. The first case is on a lambda, so I expect it to perform no forcing at all. The first case evaluates a complete application of `undefined`, so should crash. As a result, I'd expect this program to generate the following output:
```
()
test: Prelude.undefined
CallStack (from HasCallStack):
error, called at libraries/base/GHC/Err.hs:78:14 in base:GHC.Err
undefined, called at test.hs:4:15 in main:Main
```
Currently (tested on GHC 8.6.5), even the first `print f` will crash, so the behavior is actually consistent. I think this is actually a reasonable semantics, but I didn't expect it based on the difference in Core. My understanding of Core semantics might be off here.
So: Is letgeneralisation of `x` but not of `_` expected? If so, why does `let !x = undefined in ()` crash?
CC @simonpj @rae since this is a continuation of the discussion in https://gitlab.haskell.org/ghc/ghc/merge_requests/1954#note_229057.With `XBangPatterns`, the act of declaring a letbinding without using it might have a sideeffect. Consider this example:
```haskell
{# LANGUAGE BangPatterns #}
f :: ()
f = let !x = undefined in ()
g :: ()
g = let !_ = undefined in ()
main = do
print f
print g
```
Both `f` and `g` declare a variable in a strict binding that is actually dead. Surprisingly, they lead to different code. Here's the Core (GHC 8.6.5) after optimisation:
```
main
= >>
(print
@ ()
GHC.Show.$fShow()
(case \ (@ a_a2hW) >
undefined
@ 'GHC.Types.LiftedRep
@ a_a2hW
(<snip>)
of
{ __DEFAULT >
GHC.Tuple.()
}))
(print
@ ()
GHC.Show.$fShow()
(case undefined
@ 'GHC.Types.LiftedRep
@ GHC.Types.Any
(<snip>)
of
{ __DEFAULT >
GHC.Tuple.()
}))
```
Note the `/\a. undefined @LiftedRep @a` in the first scrutinee. This is ultimately due to the fact that `x` is letgeneralised, whereas `_` is not. The first case is on a lambda, so I expect it to perform no forcing at all. The first case evaluates a complete application of `undefined`, so should crash. As a result, I'd expect this program to generate the following output:
```
()
test: Prelude.undefined
CallStack (from HasCallStack):
error, called at libraries/base/GHC/Err.hs:78:14 in base:GHC.Err
undefined, called at test.hs:4:15 in main:Main
```
Currently (tested on GHC 8.6.5), even the first `print f` will crash, so the behavior is actually consistent. I think this is actually a reasonable semantics, but I didn't expect it based on the difference in Core. My understanding of Core semantics might be off here.
So: Is letgeneralisation of `x` but not of `_` expected? If so, why does `let !x = undefined in ()` crash?
CC @simonpj @rae since this is a continuation of the discussion in https://gitlab.haskell.org/ghc/ghc/merge_requests/1954#note_229057.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/17395`tcMatchTy` is terribly broken20191101T09:28:24ZSimon Peyton Jones`tcMatchTy` is terribly brokenSuppose `(T :: forall k. k > Type)` and we are matching
```
tcMatchTy (T k (a::k)) (T j (b::j))
```
Then we'll match `k :> j`, as expected. But then in `TcUnify.unify_tys`
we invoke
```
unify_tys env (a::k) (b::j) (Refl k)
```
Despite `Note [Kind coercions in Unify]` it's not clear to
me why we need that Refl coercion.
But, assuming we need it, very very bad things now happen.
In `uUnrefined` we end up adding the binding `a :> (b > Refl k)`.
Alas! Alack! `k` is one of the template variables, which we are
substituting away, so it's **terrible** if `k` appears in the
range of the substitution  it belongs only in the range.
A oneline (actually onecharacter) fix is this:
```
 = do { unify_ty env x y (mkNomReflCo $ typeKind x)
+ = do { unify_ty env x y (mkNomReflCo $ typeKind y)
```
But I am hardpressed to explain exactly why this is the correct fix.
@rae, help?
This actually bit me when working on `mkCastTy` in #17323.Suppose `(T :: forall k. k > Type)` and we are matching
```
tcMatchTy (T k (a::k)) (T j (b::j))
```
Then we'll match `k :> j`, as expected. But then in `TcUnify.unify_tys`
we invoke
```
unify_tys env (a::k) (b::j) (Refl k)
```
Despite `Note [Kind coercions in Unify]` it's not clear to
me why we need that Refl coercion.
But, assuming we need it, very very bad things now happen.
In `uUnrefined` we end up adding the binding `a :> (b > Refl k)`.
Alas! Alack! `k` is one of the template variables, which we are
substituting away, so it's **terrible** if `k` appears in the
range of the substitution  it belongs only in the range.
A oneline (actually onecharacter) fix is this:
```
 = do { unify_ty env x y (mkNomReflCo $ typeKind x)
+ = do { unify_ty env x y (mkNomReflCo $ typeKind y)
```
But I am hardpressed to explain exactly why this is the correct fix.
@rae, help?
This actually bit me when working on `mkCastTy` in #17323.8.10.1https://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/17541Regression involving unboxed types and type families20191212T16:20:40ZMatthew PickeringRegression involving unboxed types and type familiesThis program compiles with 8.6.5 and 8.8.1 but not with HEAD.
```
{# LANGUAGE
MagicHash,
FlexibleInstances,
MultiParamTypeClasses,
TypeFamilies,
PolyKinds,
DataKinds,
FunctionalDependencies,
TypeFamilyDependencies #}
module A where
import GHC.Prim
import GHC.Exts
type family Rep rep where
Rep Int = IntRep
type family Unboxed rep = (urep :: TYPE (Rep rep))  urep > rep where
Unboxed Int = Int#
```
```
[1 of 1] Compiling A ( A.hs, A.o )
A.hs:20:17: error:
• Expected kind ‘TYPE (Rep rep)’,
but ‘Int#’ has kind ‘TYPE 'IntRep’
• In the type ‘Int#’
In the type family declaration for ‘Unboxed’

20  Unboxed Int = Int#
 ^^^^
```This program compiles with 8.6.5 and 8.8.1 but not with HEAD.
```
{# LANGUAGE
MagicHash,
FlexibleInstances,
MultiParamTypeClasses,
TypeFamilies,
PolyKinds,
DataKinds,
FunctionalDependencies,
TypeFamilyDependencies #}
module A where
import GHC.Prim
import GHC.Exts
type family Rep rep where
Rep Int = IntRep
type family Unboxed rep = (urep :: TYPE (Rep rep))  urep > rep where
Unboxed Int = Int#
```
```
[1 of 1] Compiling A ( A.hs, A.o )
A.hs:20:17: error:
• Expected kind ‘TYPE (Rep rep)’,
but ‘Int#’ has kind ‘TYPE 'IntRep’
• In the type ‘Int#’
In the type family declaration for ‘Unboxed’

20  Unboxed Int = Int#
 ^^^^
```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/17562`Any` appearing in a quantified constraint20210111T13:07:45ZRichard Eisenbergrae@richarde.dev`Any` appearing in a quantified constraintIf I say
```hs
{# LANGUAGE QuantifiedConstraints, MultiParamTypeClasses #}
module Bug where
class (forall a. a b ~ a c) => C b c
```
I get
```
Bug.hs:5:1: error:
• Illegal type synonym family application ‘GHC.Types.Any
@*’ in instance:
(a b :: GHC.Types.Any @*) ~ (a c :: GHC.Types.Any @*)
• In the quantified constraint ‘forall (a :: k > GHC.Types.Any).
a b ~ a c’
In the context: forall (a :: k > GHC.Types.Any). a b ~ a c
While checking the superclasses of class ‘C’
In the class declaration for ‘C’

5  class (forall a. a b ~ a c) => C b c
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
This is a specific case of #17567. Despite superficial similarity, this is unrelated to #16775.If I say
```hs
{# LANGUAGE QuantifiedConstraints, MultiParamTypeClasses #}
module Bug where
class (forall a. a b ~ a c) => C b c
```
I get
```
Bug.hs:5:1: error:
• Illegal type synonym family application ‘GHC.Types.Any
@*’ in instance:
(a b :: GHC.Types.Any @*) ~ (a c :: GHC.Types.Any @*)
• In the quantified constraint ‘forall (a :: k > GHC.Types.Any).
a b ~ a c’
In the context: forall (a :: k > GHC.Types.Any). a b ~ a c
While checking the superclasses of class ‘C’
In the class declaration for ‘C’

5  class (forall a. a b ~ a c) => C b c
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
This is a specific case of #17567. Despite superficial similarity, this is unrelated to #16775.9.0.1Richard Eisenbergrae@richarde.devRichard Eisenbergrae@richarde.devhttps://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/17567Never `Any`ify during kind inference20210111T13:09:30ZRichard Eisenbergrae@richarde.devNever `Any`ify during kind inference#14198 concludes with a new plan: never `Any`ify during kind inference. This ticket tracks this particular problem, separate from #14198.
Here are some examples of `Any`ification during kind inference:
#17301:
```hs
data B a
data TySing ty where
SB :: TySing (B a)
data ATySing where
MkATySing :: TySing ty > ATySing
type family Forget ty :: ATySing where
Forget (B a) = MkATySing SB
```
The RHS of that type family equation is really `MkATySing @alpha (SB @alpha)`, and the `alpha` gets zonked to `Any`.
#14198:
```hs
type T = forall a. Proxy a
```
The RHS of the type synonym is really `forall (a :: kappa). Proxy @kappa a`, and the `kappa` gets zonked to `Any`.
#17562:
```hs
class (forall a. a b ~ a c) => C b c
```
The superclass constraint is really `forall (a :: Type > kappa). (~) @kappa (a b) (a c))`, and the `kappa` gets zonked to `Any`.
We want to stop zonking to `Any`, preferring to error instead. But how should we implement?
* Option A: Use a new variant of `ZonkFlexi`, a choice carried around in a `ZonkEnv` that says what to do with empty metavariables. The new choice would cause an error. This new form of `ZonkFlexi` would be used in the final zonks in e.g. TcTyClsDecls. Open question: how to get a decent error message? I think we'd have to pass around the original, toplevel type in order to report it. By the time we have just the unbound metavariable, we have no context to report.
* Option B: Similar to (A), but don't report an error in the zonker. Instead, the new variant of `ZonkFlexi` would insert some magical error type. Then, the validity checker could do an early pass, looking for the error type; it can then report a nice error message.
* Option C: Look for all cases where `Any`ification might happen, and detect each one separately. This can produce lovely error messages. The solution for #17562 in !2313 does this. Perhaps we can pair this choice with a new `ZonkFlexi` that panics. That way, we'll know if we've missed a case.
* Simon below proposes Option D: Zap to `Type` instead of `Any`. I (Richard) view D as an addon to any of the above plans. Because `Type` is not always wellkinded, we can only zap to `Type` sometimes, and we still need to decide what we do at other times. Personally, I prefer not to treat `Type` specially with XPolyKinds` enabled, and so I'd prefer that we don't do this.
* EDIT: Also, we can consider Option E: Report poor error messages, saying something about an unconstrained kind variable. Users would be helped only via the context (the "In the data declaration for `Wurble`" bits). This would mean building up useful contexts in the zonker.
* Option F: The new constructor for `ZonkFlexi` could carry the toplevel type we are trying to zonk. If we encounter an unconstrained metavariable, we just look at this bit of context to produce the error message. Perhaps this could be combined with the contextbuilding in Option E for good effect. This is the first solution I'm actually happy with.
Thoughts?#14198 concludes with a new plan: never `Any`ify during kind inference. This ticket tracks this particular problem, separate from #14198.
Here are some examples of `Any`ification during kind inference:
#17301:
```hs
data B a
data TySing ty where
SB :: TySing (B a)
data ATySing where
MkATySing :: TySing ty > ATySing
type family Forget ty :: ATySing where
Forget (B a) = MkATySing SB
```
The RHS of that type family equation is really `MkATySing @alpha (SB @alpha)`, and the `alpha` gets zonked to `Any`.
#14198:
```hs
type T = forall a. Proxy a
```
The RHS of the type synonym is really `forall (a :: kappa). Proxy @kappa a`, and the `kappa` gets zonked to `Any`.
#17562:
```hs
class (forall a. a b ~ a c) => C b c
```
The superclass constraint is really `forall (a :: Type > kappa). (~) @kappa (a b) (a c))`, and the `kappa` gets zonked to `Any`.
We want to stop zonking to `Any`, preferring to error instead. But how should we implement?
* Option A: Use a new variant of `ZonkFlexi`, a choice carried around in a `ZonkEnv` that says what to do with empty metavariables. The new choice would cause an error. This new form of `ZonkFlexi` would be used in the final zonks in e.g. TcTyClsDecls. Open question: how to get a decent error message? I think we'd have to pass around the original, toplevel type in order to report it. By the time we have just the unbound metavariable, we have no context to report.
* Option B: Similar to (A), but don't report an error in the zonker. Instead, the new variant of `ZonkFlexi` would insert some magical error type. Then, the validity checker could do an early pass, looking for the error type; it can then report a nice error message.
* Option C: Look for all cases where `Any`ification might happen, and detect each one separately. This can produce lovely error messages. The solution for #17562 in !2313 does this. Perhaps we can pair this choice with a new `ZonkFlexi` that panics. That way, we'll know if we've missed a case.
* Simon below proposes Option D: Zap to `Type` instead of `Any`. I (Richard) view D as an addon to any of the above plans. Because `Type` is not always wellkinded, we can only zap to `Type` sometimes, and we still need to decide what we do at other times. Personally, I prefer not to treat `Type` specially with XPolyKinds` enabled, and so I'd prefer that we don't do this.
* EDIT: Also, we can consider Option E: Report poor error messages, saying something about an unconstrained kind variable. Users would be helped only via the context (the "In the data declaration for `Wurble`" bits). This would mean building up useful contexts in the zonker.
* Option F: The new constructor for `ZonkFlexi` could carry the toplevel type we are trying to zonk. If we encounter an unconstrained metavariable, we just look at this bit of context to produce the error message. Perhaps this could be combined with the contextbuilding in Option E for good effect. This is the first solution I'm actually happy with.
Thoughts?https://gitlab.haskell.org/ghc/ghc//issues/17625Evidence for equality constraints on typeclass methods isn’t erased20200108T16:45:20ZAlexis KingEvidence for equality constraints on typeclass methods isn’t erasedGenerally, I expect `a ~ b` constraints to have no runtime cost, so I was surprised to discover that they sometimes do. If I understand correctly, constraints of type `a ~ b` are boxed versions of `a ~# b`, the latter of which have no runtime representation. Ordinarily, this boxing and unboxing is eliminated via worker/wrapper just like any other boxing, but worker/wrapper can only be performed at call sites to known functions, so equality constraints on typeclass methods are not erased unless the method is specialized. This program illustrates that:
```haskell
{# LANGUAGE ConstrainedClassMethods, TypeFamilies #}
module M where
type family F a
class C a where
m :: F a ~ Int => a > Bool
f :: (C a, F a ~ Int) => a > Bool
f x = not (m x)
```
Compiling with `O ddumpsimpl` reveals that the call to `m` inside `F a ~ Int` really does pass a boxed equality.
This seems silly to me. As far as I can tell, equalities are aggressively forced, so it would be entirely safe to perform a worker/wrapperesque transformation to the `C` constructor itself. Specifically, GHC could desugar `C` into the following:
```haskell
newtype C a = $WC { $wm :: F a ~# Int > a > Bool }
C :: (F a ~ Int => a > Bool) > C a
C m = $WC { $wm = m `seq` \co > m (Eq# co) }
m :: (C a, F a ~ Int) => a > Bool
m ($WC { $wm }) (Eq# co) = $wm co
```
The equality argument would be erased on both ends via the same mechanism that exists today for worker/wrapper DataCons, and the resulting program would be slightly more efficient.
Maybe there is some problem with this scheme I’m not seeing; it’s entirely possible. I don’t know all the subtleties. But seeing as it seems totally sound to me based on the investigation I’ve done so far, and since equalities *not* being erased was so surprising to me, I feel like it isn’t entirely unreasonable to consider this a bug rather than a missing feature (though that is admittedly arguable).Generally, I expect `a ~ b` constraints to have no runtime cost, so I was surprised to discover that they sometimes do. If I understand correctly, constraints of type `a ~ b` are boxed versions of `a ~# b`, the latter of which have no runtime representation. Ordinarily, this boxing and unboxing is eliminated via worker/wrapper just like any other boxing, but worker/wrapper can only be performed at call sites to known functions, so equality constraints on typeclass methods are not erased unless the method is specialized. This program illustrates that:
```haskell
{# LANGUAGE ConstrainedClassMethods, TypeFamilies #}
module M where
type family F a
class C a where
m :: F a ~ Int => a > Bool
f :: (C a, F a ~ Int) => a > Bool
f x = not (m x)
```
Compiling with `O ddumpsimpl` reveals that the call to `m` inside `F a ~ Int` really does pass a boxed equality.
This seems silly to me. As far as I can tell, equalities are aggressively forced, so it would be entirely safe to perform a worker/wrapperesque transformation to the `C` constructor itself. Specifically, GHC could desugar `C` into the following:
```haskell
newtype C a = $WC { $wm :: F a ~# Int > a > Bool }
C :: (F a ~ Int => a > Bool) > C a
C m = $WC { $wm = m `seq` \co > m (Eq# co) }
m :: (C a, F a ~ Int) => a > Bool
m ($WC { $wm }) (Eq# co) = $wm co
```
The equality argument would be erased on both ends via the same mechanism that exists today for worker/wrapper DataCons, and the resulting program would be slightly more efficient.
Maybe there is some problem with this scheme I’m not seeing; it’s entirely possible. I don’t know all the subtleties. But seeing as it seems totally sound to me based on the investigation I’ve done so far, and since equalities *not* being erased was so surprising to me, I feel like it isn’t entirely unreasonable to consider this a bug rather than a missing feature (though that is admittedly arguable).https://gitlab.haskell.org/ghc/ghc//issues/17633Closed type family declaration accepts any name in LHS20200103T21:33:08ZMaxim KoltsovClosed type family declaration accepts any name in LHS## Summary
Closed type family declaration will accept (almost) any name instead of family's name left of `=`.
## Steps to reproduce
```haskell
{# LANGUAGE TypeFamilies #}
module WTF where
type family Bar (a :: *) :: * where
Bar Int = ()
type family Foo (a :: *) :: * where
Bar Int = Bool
Bar Bool = Int
Bar a = a
```
When loaded to ghci, this file not only compiles, but works as if `Foo` were defined the normal way:
```
λ> :kind! Bar Int
Bar Int :: *
= ()
λ> :kind! Bar Bool
Bar Bool :: *
= Bar Bool
λ> :kind! Foo Int
Foo Int :: *
= Bool
λ> :kind! Foo Bool
Foo Bool :: *
= Int
λ> :kind! Foo Char
Foo Char :: *
= Char
```
It's clear that `Foo` is defined as it should be and that `Bar` is not broken by this definition.
## Expected behavior
GHC should emit an error in this case, as this code seems very strange.
Curiously, if `Bar` is not in scope GHC detects an error at `Foo`'s definition:
```
<interactive>:5:3: error:
Not in scope: type constructor or class ‘Bar’
```
Moreover, if I try to use some family from another module, it fails as well:
```
> import GHC.Generics
> :{
 type family Foo (a :: *) where
 Rep Bool = Maybe
 :}
<interactive>:6:3: error:
• Mismatched type name in type family instance.
Expected: Foo
Actual: Rep
```
## Environment
* GHC version used:
```console
$ stack exec  ghc V
The Glorious Glasgow Haskell Compilation System, version 8.6.3
```
* Operating System: macOS## Summary
Closed type family declaration will accept (almost) any name instead of family's name left of `=`.
## Steps to reproduce
```haskell
{# LANGUAGE TypeFamilies #}
module WTF where
type family Bar (a :: *) :: * where
Bar Int = ()
type family Foo (a :: *) :: * where
Bar Int = Bool
Bar Bool = Int
Bar a = a
```
When loaded to ghci, this file not only compiles, but works as if `Foo` were defined the normal way:
```
λ> :kind! Bar Int
Bar Int :: *
= ()
λ> :kind! Bar Bool
Bar Bool :: *
= Bar Bool
λ> :kind! Foo Int
Foo Int :: *
= Bool
λ> :kind! Foo Bool
Foo Bool :: *
= Int
λ> :kind! Foo Char
Foo Char :: *
= Char
```
It's clear that `Foo` is defined as it should be and that `Bar` is not broken by this definition.
## Expected behavior
GHC should emit an error in this case, as this code seems very strange.
Curiously, if `Bar` is not in scope GHC detects an error at `Foo`'s definition:
```
<interactive>:5:3: error:
Not in scope: type constructor or class ‘Bar’
```
Moreover, if I try to use some family from another module, it fails as well:
```
> import GHC.Generics
> :{
 type family Foo (a :: *) where
 Rep Bool = Maybe
 :}
<interactive>:6:3: error:
• Mismatched type name in type family instance.
Expected: Foo
Actual: Rep
```
## Environment
* GHC version used:
```console
$ stack exec  ghc V
The Glorious Glasgow Haskell Compilation System, version 8.6.3
```
* Operating System: macOS8.8.1https://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/17672Never kick out Given Nominal equalities20210413T14:16:56ZRichard Eisenbergrae@richarde.devNever kick out Given Nominal equalitiesIn other explorations (#17323 and friends) Simon and I determined that a Given Nominal equality should never be kicked out. Why? Because the mutable update of a unification variable should really behave just like a given nominal equality (really, the solver should be pure, but that would be inefficient). Mutable variable updates can't get revisited (i.e. kicked out), so neither should given nominal equalities. And we almost have this property. Here is the relevant text:
Lemma: Nominal Given equalities are never kicked out. Proof: Let `a fw> t` be a work item and `b G/N> s` be an inert equality. We must show that, regardless of `a`, `t`, `b`, and `s`, condition K from the Note always hold. (Condition K is the "keep" condition.)
K0 is true when `fw /= G/N`. If K0 is true, then K is true, and we are done. So, we assume that `fw = G/N`.
We must show all of K1K3.
K1: `not (a = b)`. This must be true, because if `a = b`, then `a` would have been rewritten during canonicalization. This is the case because `G/N >= G/N`.
K2: `not (G/N >= G/N) OR G/N >= G/N OR ...`. True by the law of the excluded middle.
K3: Actually, only K3a applies, because the role is nominal: `s /= a`. Actually, we might indeed have `s = a`. But we still shouldn't kick out; see Note \[K3: completeness of solving\], which makes this clear. So, **Action Item**: modify the kickout conditions so that this proof holds.
QED.
We think the new keep condition should be `s /= a && t /= b`. This ticket is to doublecheck this intuition and execute.
We believe that there is no loop or other misbehavior here. It's just good hygiene to have given nominals and metavar unifications to be treated identically within the solver. And less kicking out is good, all else being equal.In other explorations (#17323 and friends) Simon and I determined that a Given Nominal equality should never be kicked out. Why? Because the mutable update of a unification variable should really behave just like a given nominal equality (really, the solver should be pure, but that would be inefficient). Mutable variable updates can't get revisited (i.e. kicked out), so neither should given nominal equalities. And we almost have this property. Here is the relevant text:
Lemma: Nominal Given equalities are never kicked out. Proof: Let `a fw> t` be a work item and `b G/N> s` be an inert equality. We must show that, regardless of `a`, `t`, `b`, and `s`, condition K from the Note always hold. (Condition K is the "keep" condition.)
K0 is true when `fw /= G/N`. If K0 is true, then K is true, and we are done. So, we assume that `fw = G/N`.
We must show all of K1K3.
K1: `not (a = b)`. This must be true, because if `a = b`, then `a` would have been rewritten during canonicalization. This is the case because `G/N >= G/N`.
K2: `not (G/N >= G/N) OR G/N >= G/N OR ...`. True by the law of the excluded middle.
K3: Actually, only K3a applies, because the role is nominal: `s /= a`. Actually, we might indeed have `s = a`. But we still shouldn't kick out; see Note \[K3: completeness of solving\], which makes this clear. So, **Action Item**: modify the kickout conditions so that this proof holds.
QED.
We think the new keep condition should be `s /= a && t /= b`. This ticket is to doublecheck this intuition and execute.
We believe that there is no loop or other misbehavior here. It's just good hygiene to have given nominals and metavar unifications to be treated identically within the solver. And less kicking out is good, all else being equal.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/17710Polykinded rewrite rule fails to typecheck (HEAD only)20200315T18:51:16ZRyan ScottPolykinded rewrite rule fails to typecheck (HEAD only)I originally noticed this issue since it prevents the `freealgebras0.0.8.1` library from building with HEAD (build log [here](https://gitlab.haskell.org/RyanGlScott/head.hackage//jobs/240129)). Here is a minimized example that demonstrates the issue:
```hs
{# LANGUAGE PolyKinds #}
{# LANGUAGE RankNTypes #}
module Bug where
import Data.Proxy
foo :: forall k (b :: k). (forall (a :: k). Proxy a > Proxy a) > Proxy b
foo g = g Proxy
{# INLINABLE [1] foo #}
{# RULES "foo" forall (g :: forall (a :: k). Proxy a > Proxy a). foo g = g Proxy #}
```
This typechecks on GHC 8.8.2 and 8.10.1alpha2, but on HEAD it fails to typecheck:
```
$ ~/Software/ghc5/inplace/bin/ghcstage2 Bug.hs
[1 of 1] Compiling Bug ( Bug.hs, Bug.o )
Bug.hs:10:11: error:
• Cannot generalise type; skolem ‘k’ would escape its scope
if I tried to quantify (b0 :: k) in this type:
forall k. Proxy @{k} b0
(Indeed, I sometimes struggle even printing this correctly,
due to its illscoped nature.)
• When checking the transformation rule "foo"

10  {# RULES "foo" forall (g :: forall (a :: k). Proxy a > Proxy a). foo g = g Proxy #}
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
Judging by the error message, this regression was likely introduced in commit 350e2b78788d47255d27489dfc62d664498b5de4 (`Don't zap to Any; error instead`). cc'ing @rae, the author of that commit.I originally noticed this issue since it prevents the `freealgebras0.0.8.1` library from building with HEAD (build log [here](https://gitlab.haskell.org/RyanGlScott/head.hackage//jobs/240129)). Here is a minimized example that demonstrates the issue:
```hs
{# LANGUAGE PolyKinds #}
{# LANGUAGE RankNTypes #}
module Bug where
import Data.Proxy
foo :: forall k (b :: k). (forall (a :: k). Proxy a > Proxy a) > Proxy b
foo g = g Proxy
{# INLINABLE [1] foo #}
{# RULES "foo" forall (g :: forall (a :: k). Proxy a > Proxy a). foo g = g Proxy #}
```
This typechecks on GHC 8.8.2 and 8.10.1alpha2, but on HEAD it fails to typecheck:
```
$ ~/Software/ghc5/inplace/bin/ghcstage2 Bug.hs
[1 of 1] Compiling Bug ( Bug.hs, Bug.o )
Bug.hs:10:11: error:
• Cannot generalise type; skolem ‘k’ would escape its scope
if I tried to quantify (b0 :: k) in this type:
forall k. Proxy @{k} b0
(Indeed, I sometimes struggle even printing this correctly,
due to its illscoped nature.)
• When checking the transformation rule "foo"

10  {# RULES "foo" forall (g :: forall (a :: k). Proxy a > Proxy a). foo g = g Proxy #}
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
Judging by the error message, this regression was likely introduced in commit 350e2b78788d47255d27489dfc62d664498b5de4 (`Don't zap to Any; error instead`). cc'ing @rae, the author of that commit.9.0.1https://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/17772CUSKless class typechecks on 8.4, but not on 8.6+20210331T17:39:10ZRyan ScottCUSKless class typechecks on 8.4, but not on 8.6+This code will typecheck with GHC 8.0.2 through 8.4.4:
```hs
{# LANGUAGE ScopedTypeVariables #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE TypeInType #}
module Bug where
import Data.Kind
import Data.Proxy
class C f where
type T (x :: f a) :: Type
sT :: forall a (x :: f a).
Proxy x > T x
```
However, it mysteriously _does_ not typecheck on GHC 8.6.5 or later:
```
$ /opt/ghc/8.8.2/bin/ghc Bug.hs
[1 of 1] Compiling Bug ( Bug.hs, Bug.o )
Bug.hs:13:22: error:
• Expected kind ‘f a’, but ‘x’ has kind ‘f a1’
• In the first argument of ‘T’, namely ‘x’
In the type signature: sT :: forall a (x :: f a). Proxy x > T x
In the class declaration for ‘C’

13  Proxy x > T x
 ^
```
I cannot think of a good reason why this shouldn't typecheck, especially since there appears to be no polymorphic recursion happening in `C`, `T`, or `sT`.
Some observations:
* Giving `C` a CUSK (i.e., `class C (f :: k > Type) where ...`) makes it typecheck:
* Splitting up `C` into two classes like so also makes it typecheck:
```hs
class C1 f where
type T (x :: f a) :: Type
class C2 f where
sT :: forall a (x :: f a).
Proxy x > T x
```This code will typecheck with GHC 8.0.2 through 8.4.4:
```hs
{# LANGUAGE ScopedTypeVariables #}
{# LANGUAGE TypeFamilies #}
{# LANGUAGE TypeInType #}
module Bug where
import Data.Kind
import Data.Proxy
class C f where
type T (x :: f a) :: Type
sT :: forall a (x :: f a).
Proxy x > T x
```
However, it mysteriously _does_ not typecheck on GHC 8.6.5 or later:
```
$ /opt/ghc/8.8.2/bin/ghc Bug.hs
[1 of 1] Compiling Bug ( Bug.hs, Bug.o )
Bug.hs:13:22: error:
• Expected kind ‘f a’, but ‘x’ has kind ‘f a1’
• In the first argument of ‘T’, namely ‘x’
In the type signature: sT :: forall a (x :: f a). Proxy x > T x
In the class declaration for ‘C’

13  Proxy x > T x
 ^
```
I cannot think of a good reason why this shouldn't typecheck, especially since there appears to be no polymorphic recursion happening in `C`, `T`, or `sT`.
Some observations:
* Giving `C` a CUSK (i.e., `class C (f :: k > Type) where ...`) makes it typecheck:
* Splitting up `C` into two classes like so also makes it typecheck:
```hs
class C1 f where
type T (x :: f a) :: Type
class C2 f where
sT :: forall a (x :: f a).
Proxy x > T x
```https://gitlab.haskell.org/ghc/ghc//issues/17789Instantiation doesn't look through dictionaries20200205T11:16:36ZRichard Eisenbergrae@richarde.devInstantiation doesn't look through dictionariesThe bug is simple to state in terms of GHC's implementation: `topInstantiate` does not look past dictionaries. Thus a type like `forall a. C a => forall b. ...` only gets its `a` instantiated, not its `b`. This can be witnessed is some uglylooking code:
```hs
data Rec a b = MkRec { x :: Bool }
class C a where
r :: Rec a b
instance C Int where
r = MkRec { x = True }
foo :: Rec Int Bool
foo = r { x = False }
```
This fails with
```
/Users/rae/temp/Bug.hs:10:7: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘r’
prevents the constraint ‘(C a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instance exist:
instance C Int  Defined at /Users/rae/temp/Bug.hs:6:10
• In the expression: r
In the expression: r {x = False}
In an equation for ‘foo’: foo = r {x = False}
```
I have no idea why it's an ambiguousvariable error, but let's not get distracted by that. The problem is that GHC does not instantiate `r` vigorously enough to notice that it's a record. The solution is straightforward: have `topInstantiate` be recursive, looking past dictionaries. `topInstantiate` is used in other places, too, and perhaps there are other similar bugs to find.The bug is simple to state in terms of GHC's implementation: `topInstantiate` does not look past dictionaries. Thus a type like `forall a. C a => forall b. ...` only gets its `a` instantiated, not its `b`. This can be witnessed is some uglylooking code:
```hs
data Rec a b = MkRec { x :: Bool }
class C a where
r :: Rec a b
instance C Int where
r = MkRec { x = True }
foo :: Rec Int Bool
foo = r { x = False }
```
This fails with
```
/Users/rae/temp/Bug.hs:10:7: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘r’
prevents the constraint ‘(C a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instance exist:
instance C Int  Defined at /Users/rae/temp/Bug.hs:6:10
• In the expression: r
In the expression: r {x = False}
In an equation for ‘foo’: foo = r {x = False}
```
I have no idea why it's an ambiguousvariable error, but let's not get distracted by that. The problem is that GHC does not instantiate `r` vigorously enough to notice that it's a record. The solution is straightforward: have `topInstantiate` be recursive, looking past dictionaries. `topInstantiate` is used in other places, too, and perhaps there are other similar bugs to find.https://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/17827Deduplicate overlapping Notes [TyVar/TyVar orientation] in TcUnify and [Canon...20200214T16:54:11ZRichard Eisenbergrae@richarde.devDeduplicate overlapping Notes [TyVar/TyVar orientation] in TcUnify and [Canonical orientation for tyvar/tyvar equality constraints] in TcCanonicalThese Notes cover similar ground but say different things.These Notes cover similar ground but say different things.https://gitlab.haskell.org/ghc/ghc//issues/17841"No skolem info" panic with PolyKinds20201019T09:16:46ZJakob Brünker"No skolem info" panic with PolyKinds## Summary
Making a class with a kindpolymorphic parameter and a single method can lead to a GHC panic stating "No skolem info".
## Steps to reproduce
The following program
```haskell
{# LANGUAGE PolyKinds #}
data Proxy a = Proxy
class Foo (t :: k) where foo :: Proxy (a :: t)
```
results in the error
```
Bug.hs:5:40: error:ghc: panic! (the 'impossible' happened)
(GHC version 8.11.0.20200215:
No skolem info:
[k_a1q3[sk:1]]
Call stack:
CallStack (from HasCallStack):
callStackDoc, called at compiler/utils/Outputable.hs:1187:37 in ghc:Outputable
pprPanic, called at compiler/typecheck/TcErrors.hs:2793:17 in ghc:TcErrors
```
On 8.6.5, it instead emits the error message
```
Bug.hs:5:45: error:
• Expected a type, but ‘t’ has kind ‘k’
• In the kind ‘t’
In the first argument of ‘Proxy’, namely ‘(a :: t)’
In the type signature: foo :: Proxy (a :: t)

5  class Foo (t :: k) where foo :: Proxy (a :: t)

```
I thought at first it might be https://gitlab.haskell.org/ghc/ghc/issues/16245 but for the facts that that issue specifically mentions RankNTypes, and produces an error already on GHC 8.6, which this example doesn't.
## Expected behavior
It should probably emit the same error message it emitted in 8.6.
## Environment
* GHC versions used: 8.8.1, HEAD
* Does *not* happen on 8.6.5
Optional:
* Operating System: linux
* System Architecture: x86_64## Summary
Making a class with a kindpolymorphic parameter and a single method can lead to a GHC panic stating "No skolem info".
## Steps to reproduce
The following program
```haskell
{# LANGUAGE PolyKinds #}
data Proxy a = Proxy
class Foo (t :: k) where foo :: Proxy (a :: t)
```
results in the error
```
Bug.hs:5:40: error:ghc: panic! (the 'impossible' happened)
(GHC version 8.11.0.20200215:
No skolem info:
[k_a1q3[sk:1]]
Call stack:
CallStack (from HasCallStack):
callStackDoc, called at compiler/utils/Outputable.hs:1187:37 in ghc:Outputable
pprPanic, called at compiler/typecheck/TcErrors.hs:2793:17 in ghc:TcErrors
```
On 8.6.5, it instead emits the error message
```
Bug.hs:5:45: error:
• Expected a type, but ‘t’ has kind ‘k’
• In the kind ‘t’
In the first argument of ‘Proxy’, namely ‘(a :: t)’
In the type signature: foo :: Proxy (a :: t)

5  class Foo (t :: k) where foo :: Proxy (a :: t)

```
I thought at first it might be https://gitlab.haskell.org/ghc/ghc/issues/16245 but for the facts that that issue specifically mentions RankNTypes, and produces an error already on GHC 8.6, which this example doesn't.
## Expected behavior
It should probably emit the same error message it emitted in 8.6.
## Environment
* GHC versions used: 8.8.1, HEAD
* Does *not* happen on 8.6.5
Optional:
* Operating System: linux
* System Architecture: x86_648.10.2https://gitlab.haskell.org/ghc/ghc//issues/17873Lazy instantiation is incompatible with implicit parameters20200715T09:06:16ZRichard Eisenbergrae@richarde.devLazy instantiation is incompatible with implicit parametersIn thinking about issues around #17173, I came up with this silliness:
```hs
getx :: (?x :: Bool > Bool) => Bool > Bool
getx = ?x
z3 = (let ?x = not in getx) False
```
GHC's current response is utter garbage:
```
Scratch.hs:52:23: error:
• Couldn't match type ‘?x::Bool > Bool’ with ‘Bool’
Expected type: Bool > Bool > Bool
Actual type: (?x::Bool > Bool) => Bool > Bool
• In the expression: getx
In the expression: let ?x = not in getx
In the expression: (let ?x = not in getx) False

52  z3 = (let ?x = not in getx) False

```
The "couldn't match type" bit is illkinded, and I have no idea why GHC is expecting `Bool > Bool > Bool` here. But the root cause, I believe, is lazy instantiation. Functions are instantiated lazily. So the `let ?x = not in getx` is instantiated lazily. The body of a `let` inherits its instantiation behavior from the outer context. So the `getx` is instantiated lazily. This means that GHC happily infers type `(?x :: Bool > Bool) => Bool > Bool` for `getx`. And then, with no incentive to instantiate, it infers `(let ?x = not in getx) :: (?x :: Bool > Bool) => Bool > Bool`. Now, when we apply such a thing to a term argument, GHC instantiates. But, lo!, there is no longer a `?x :: Bool > Bool` constraint in scope, causing unhappiness.
If we instantiate eagerly, I claim this should all work just fine.
I believe this will be fixed alongside #17173, but given that #17173 is about general improvement rather than bugfixing, I made this outright bug a separate ticket.In thinking about issues around #17173, I came up with this silliness:
```hs
getx :: (?x :: Bool > Bool) => Bool > Bool
getx = ?x
z3 = (let ?x = not in getx) False
```
GHC's current response is utter garbage:
```
Scratch.hs:52:23: error:
• Couldn't match type ‘?x::Bool > Bool’ with ‘Bool’
Expected type: Bool > Bool > Bool
Actual type: (?x::Bool > Bool) => Bool > Bool
• In the expression: getx
In the expression: let ?x = not in getx
In the expression: (let ?x = not in getx) False

52  z3 = (let ?x = not in getx) False

```
The "couldn't match type" bit is illkinded, and I have no idea why GHC is expecting `Bool > Bool > Bool` here. But the root cause, I believe, is lazy instantiation. Functions are instantiated lazily. So the `let ?x = not in getx` is instantiated lazily. The body of a `let` inherits its instantiation behavior from the outer context. So the `getx` is instantiated lazily. This means that GHC happily infers type `(?x :: Bool > Bool) => Bool > Bool` for `getx`. And then, with no incentive to instantiate, it infers `(let ?x = not in getx) :: (?x :: Bool > Bool) => Bool > Bool`. Now, when we apply such a thing to a term argument, GHC instantiates. But, lo!, there is no longer a `?x :: Bool > Bool` constraint in scope, causing unhappiness.
If we instantiate eagerly, I claim this should all work just fine.
I believe this will be fixed alongside #17173, but given that #17173 is about general improvement rather than bugfixing, I made this outright bug a separate ticket.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/17955mkNewTyConRhs panic when trying to constrain newtype with Coercible20210123T06:44:33ZmatzemathicsmkNewTyConRhs panic when trying to constrain newtype with Coercible## Summary
The following code panics in ghc 8.8.3:
```haskell
{# LANGUAGE FlexibleContexts #}
import Data.Coerce
newtype T = Coercible () T => T ()
```
Error message:
```
[1 of 1] Compiling Main ( abug.hs, abug.o )
ghc: panic! (the 'impossible' happened)
(GHC version 8.8.3 for x86_64unknownlinux):
mkNewTyConRhs
T [Coercible () T, ()]
Call stack:
CallStack (from HasCallStack):
callStackDoc, called at compiler/utils/Outputable.hs:1159:37 in ghc:Outputable
pprPanic, called at compiler/iface/BuildTyCl.hs:65:27 in ghc:BuildTyCl
```
This seems to come from whatever is done to infer Coercible's instances.
Any other Constraint (weather or not using a multi parameter class) gives an error message:
```haskell
{# LANGUAGE FlexibleContexts #}
newtype T = Show T => T ()
```
results in:
```
[1 of 1] Compiling Main ( abug.hs, abug.o )
abug.hs:3:13: error:
* A newtype constructor cannot have a context in its type
T :: Show T => () > T
* In the definition of data constructor `T'
In the newtype declaration for `T'

3  newtype T = Show T => T ()
 ^^^^^^^^^^^^^^
```
## Expected behavior
Should most likely print an error message as in the second example.
## Environment
* GHC version used: 8.8.3## Summary
The following code panics in ghc 8.8.3:
```haskell
{# LANGUAGE FlexibleContexts #}
import Data.Coerce
newtype T = Coercible () T => T ()
```
Error message:
```
[1 of 1] Compiling Main ( abug.hs, abug.o )
ghc: panic! (the 'impossible' happened)
(GHC version 8.8.3 for x86_64unknownlinux):
mkNewTyConRhs
T [Coercible () T, ()]
Call stack:
CallStack (from HasCallStack):
callStackDoc, called at compiler/utils/Outputable.hs:1159:37 in ghc:Outputable
pprPanic, called at compiler/iface/BuildTyCl.hs:65:27 in ghc:BuildTyCl
```
This seems to come from whatever is done to infer Coercible's instances.
Any other Constraint (weather or not using a multi parameter class) gives an error message:
```haskell
{# LANGUAGE FlexibleContexts #}
newtype T = Show T => T ()
```
results in:
```
[1 of 1] Compiling Main ( abug.hs, abug.o )
abug.hs:3:13: error:
* A newtype constructor cannot have a context in its type
T :: Show T => () > T
* In the definition of data constructor `T'
In the newtype declaration for `T'

3  newtype T = Show T => T ()
 ^^^^^^^^^^^^^^
```
## Expected behavior
Should most likely print an error message as in the second example.
## Environment
* GHC version used: 8.8.39.0.1https://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/18073Outofdate commentary in Tc.Deriv.Infer20200423T03:49:06ZRichard Eisenbergrae@richarde.devOutofdate commentary in Tc.Deriv.InferCheck out https://gitlab.haskell.org/ghc/ghc//blob/15ab6cd548f284732a7f89d78c2b89b1bfc4ea1d/compiler/GHC/Tc/Deriv/Infer.hs#L805
* The commentary there talks about creating a variable `unsolved`, which does not seem to exist.
* In addition, the partition below creates `bad`, which is just ignored. Maybe this is right  I have not thought about it. But if it is right, it should be documented.
cc @RyanGlScottCheck out https://gitlab.haskell.org/ghc/ghc//blob/15ab6cd548f284732a7f89d78c2b89b1bfc4ea1d/compiler/GHC/Tc/Deriv/Infer.hs#L805
* The commentary there talks about creating a variable `unsolved`, which does not seem to exist.
* In addition, the partition below creates `bad`, which is just ignored. Maybe this is right  I have not thought about it. But if it is right, it should be documented.
cc @RyanGlScotthttps://gitlab.haskell.org/ghc/ghc//issues/18151Etaexpansion of a leftsection20210112T23:04:49ZRichard Eisenbergrae@richarde.devEtaexpansion of a leftsectionIf I say
```hs
x = seq (True `undefined`) ()
```
what should I get when evaluating `x`?
According to my understanding of the Haskell Report, I should get `()`. And according to my understanding of GHC's source code (in `GHC.Tc.Gen.Expr`), I should get `()`. But I get an exception.
Why?
NB: `XPostfixOperators` is off. If it were on, the exception would be expected.
Spun off from https://github.com/ghcproposals/ghcproposals/pull/275#issuecomment624282022If I say
```hs
x = seq (True `undefined`) ()
```
what should I get when evaluating `x`?
According to my understanding of the Haskell Report, I should get `()`. And according to my understanding of GHC's source code (in `GHC.Tc.Gen.Expr`), I should get `()`. But I get an exception.
Why?
NB: `XPostfixOperators` is off. If it were on, the exception would be expected.
Spun off from https://github.com/ghcproposals/ghcproposals/pull/275#issuecomment6242820229.0.1Vladislav ZavialovVladislav Zavialovhttps://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/18300UnliftedNewtypesDifficultUnification broken due to simplified subsumption20200703T21:33:23ZBen GamariUnliftedNewtypesDifficultUnification broken due to simplified subsumption`UnliftedNewtypesDifficultUnification` fails due to simplified subsumption patch (!2600) in `DEBUG`enabled compiler.
```
Compile failed (exit code 1) errors were:
ghcstage2: panic! (the 'impossible' happened)
(GHC version 8.11.0.20200603:
ASSERT failed! file compiler/GHC/Core/FamInstEnv.hs, line 651
Please report this as a GHC bug: https://www.haskell.org/ghc/reportabug
*** unexpected failure for UnliftedNewtypesDifficultUnification(normal)
```
I have marked this test as broken in the interest of getting !2600 merged.
As seen in Job [#356282](https://gitlab.haskell.org/ghc/ghc//jobs/356282).`UnliftedNewtypesDifficultUnification` fails due to simplified subsumption patch (!2600) in `DEBUG`enabled compiler.
```
Compile failed (exit code 1) errors were:
ghcstage2: panic! (the 'impossible' happened)
(GHC version 8.11.0.20200603:
ASSERT failed! file compiler/GHC/Core/FamInstEnv.hs, line 651
Please report this as a GHC bug: https://www.haskell.org/ghc/reportabug
*** unexpected failure for UnliftedNewtypesDifficultUnification(normal)
```
I have marked this test as broken in the interest of getting !2600 merged.
As seen in Job [#356282](https://gitlab.haskell.org/ghc/ghc//jobs/356282).9.0.1Simon Peyton JonesSimon Peyton Joneshttps://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/18412Monotype check for case branches should not recur through arrows20200720T07:57:36ZRichard Eisenbergrae@richarde.devMonotype check for case branches should not recur through arrowsConsider this module:
```hs
{# LANGUAGE RankNTypes #}
module Bug where
hr :: (forall a. a > a) > ()
hr _ = ()
foo x = case x of () > hr
bar x = case x of True > hr
False > hr
```
On HEAD, `foo` is accepted while `bar` is rejected. (This is not a change from previous behavior.) The reason is that GHC requires `case` branches (when there are more than 1; and when the result of the `case` is being inferred, not checked) to have monotypes, lest it be left with the task of finding the most general supertype of a bunch of polytypes. However, now that we have simplified subsumption, it is draconian to propagate the monotype check past arrows. I thus claim that `bar` should be accepted.Consider this module:
```hs
{# LANGUAGE RankNTypes #}
module Bug where
hr :: (forall a. a > a) > ()
hr _ = ()
foo x = case x of () > hr
bar x = case x of True > hr
False > hr
```
On HEAD, `foo` is accepted while `bar` is rejected. (This is not a change from previous behavior.) The reason is that GHC requires `case` branches (when there are more than 1; and when the result of the `case` is being inferred, not checked) to have monotypes, lest it be left with the task of finding the most general supertype of a bunch of polytypes. However, now that we have simplified subsumption, it is draconian to propagate the monotype check past arrows. I thus claim that `bar` should be accepted.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/18439Pattern guards can break linearity20210108T16:49:06ZArnaud SpiwackPattern guards can break linearity## Summary
Patterns, in patternguards guards are not checked for linearity. Which let's us write incorrect program with respect to linearity. The linter rightfully rejects those.
## Steps to reproduce
This typechecks but should not:
```
{# LANGUAGE LinearTypes #}
unsafeConsume :: a #> ()
unsafeConsume x  _ < x = ()
```
## Environment
* GHC version used: master 3656dff8259199d0dab2d1a1f1b887c252a9c1a3
## Note
Originally reported by Roman Cheplyaka.## Summary
Patterns, in patternguards guards are not checked for linearity. Which let's us write incorrect program with respect to linearity. The linter rightfully rejects those.
## Steps to reproduce
This typechecks but should not:
```
{# LANGUAGE LinearTypes #}
unsafeConsume :: a #> ()
unsafeConsume x  _ < x = ()
```
## Environment
* GHC version used: master 3656dff8259199d0dab2d1a1f1b887c252a9c1a3
## Note
Originally reported by Roman Cheplyaka.Arnaud SpiwackArnaud Spiwackhttps://gitlab.haskell.org/ghc/ghc//issues/18451Infinite loop during kind inference20200727T08:10:18ZSimon Peyton JonesInfinite loop during kind inferenceThis program
```
{# LANGUAGE RankNTypes #}
{# LANGUAGE TypeInType #}
module Bug where
import Data.Kind
type Const a b = a
data SameKind :: k > k > Type
type T (k :: Const Type a) = forall (b :: k). SameKind a b
```
goes into an infinite loop during kind checking. (Extracted from #16245.)
We have
```
a_agk :: k_au5
k_atM :: Const Type a_agk
k_au5 := k_au7
```
and then we try to unify `k_au7 := k_atM`. That should be an occurscheck error, since `k_atM`'s kind mentions `a_agk`, whose kind mentions `k_au5`, which is equal to `k_au7`.
But `occCheckExpand` (called from `GHC.Tc.Utils.Unify.metaTyVarUpdateOK`) expands the `Const` synonym in `k_atM`'s kind so that it no longer mentions `a_agk`, which allows the update to go ahead.
Wrong! We can't do this `occCheckExpand` business inside kinds! Let's just not do that.This program
```
{# LANGUAGE RankNTypes #}
{# LANGUAGE TypeInType #}
module Bug where
import Data.Kind
type Const a b = a
data SameKind :: k > k > Type
type T (k :: Const Type a) = forall (b :: k). SameKind a b
```
goes into an infinite loop during kind checking. (Extracted from #16245.)
We have
```
a_agk :: k_au5
k_atM :: Const Type a_agk
k_au5 := k_au7
```
and then we try to unify `k_au7 := k_atM`. That should be an occurscheck error, since `k_atM`'s kind mentions `a_agk`, whose kind mentions `k_au5`, which is equal to `k_au7`.
But `occCheckExpand` (called from `GHC.Tc.Utils.Unify.metaTyVarUpdateOK`) expands the `Const` synonym in `k_atM`'s kind so that it no longer mentions `a_agk`, which allows the update to go ahead.
Wrong! We can't do this `occCheckExpand` business inside kinds! Let's just not do that.https://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/18481Improve instantiation of datacons20210507T20:05:28ZKrzysztof GogolewskiImprove instantiation of dataconsThis ticket tracks a possible improvement to `return_data_con`.
When typechecking a datacon `T`, do we instantiate its arguments? We'd like to avoid instantiation, because it breaks VTA.
Currently, we instantiate levitypolymorphic constructors. Quoting Note [Linear fields generalization]:
```
A small hitch: if the constructor is levitypolymorphic (unboxed tuples, sums,
certain newtypes with XUnliftedNewtypes) then this strategy produces
\r1 r2 a b (x # p :: a) (y # q :: b) > (# a, b #)
Which has type
forall r1 r2 a b. a #p> b #q> (# a, b #)
Which violates the levitypolymorphism restriction see Note [Levity polymorphism
checking] in DsMonad.
So we really must instantiate r1 and r2 rather than quantify over them. For
simplicity, we just instantiate the entire type, as described in Note
[Instantiating stupid theta]. It breaks visible type application with unboxed
tuples, sums and levitypolymorphic newtypes, but this doesn't appear to be used
anywhere.
A better plan: let's force all representation variable to be *inferred*, so that
they are not subject to visible type applications. Then we can instantiate
inferred argument eagerly.
```
The goal of this ticket is to implement the last paragraph.This ticket tracks a possible improvement to `return_data_con`.
When typechecking a datacon `T`, do we instantiate its arguments? We'd like to avoid instantiation, because it breaks VTA.
Currently, we instantiate levitypolymorphic constructors. Quoting Note [Linear fields generalization]:
```
A small hitch: if the constructor is levitypolymorphic (unboxed tuples, sums,
certain newtypes with XUnliftedNewtypes) then this strategy produces
\r1 r2 a b (x # p :: a) (y # q :: b) > (# a, b #)
Which has type
forall r1 r2 a b. a #p> b #q> (# a, b #)
Which violates the levitypolymorphism restriction see Note [Levity polymorphism
checking] in DsMonad.
So we really must instantiate r1 and r2 rather than quantify over them. For
simplicity, we just instantiate the entire type, as described in Note
[Instantiating stupid theta]. It breaks visible type application with unboxed
tuples, sums and levitypolymorphic newtypes, but this doesn't appear to be used
anywhere.
A better plan: let's force all representation variable to be *inferred*, so that
they are not subject to visible type applications. Then we can instantiate
inferred argument eagerly.
```
The goal of this ticket is to implement the last paragraph.https://gitlab.haskell.org/ghc/ghc//issues/18529GHC fails to infer type with FlexibleContexts20200930T21:32:01ZRichard 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.dev