Unhelpful and misleading coercion error when constructor not in scope
Summary
An attempt to coerce
a value inside a data constructor where the constructor is not in scope fails, as expected. But the error message given by GHC does not report the true problem (the lack of constructor), and instead seems to suggest the coercion fails because the contained types are incompatible. This error message is extremely misleading.
Steps to reproduce
A.hs:
{-# language RoleAnnotations #-}
module A where
type role A nominal
data A a = A a
mkA :: a -> A a
mkA = A
B.hs:
module B where
import A ( A, mkA )
import Data.Coerce ( coerce )
newtype Box = Box Int
aInt = mkA 3 :: A Int
-- raises an error:
-- • Couldn't match type ‘Int’ with ‘Box’
-- arising from a use of ‘coerce’
aBox = coerce aInt :: A Box
Expected behavior
I expect an error which tells me that the problem is that the constructor A
is not in scope, not an error that suggests that I can't coerce from Int
to Box
.
This may also be related to the problem described in #15850.
Environment
- GHC version used: 8.10.6 (from Stackage LTS 18.7).