GHC is overly lax when typechecking bundled pattern synonyms
Summary
When a pattern synonym is bundled with a type, the type of the pattern synonym is required to match. This can be circumvented by giving the pattern a type annotation in which the head is polymorphic, but the context constrains it to be a type other than what it is being bundled with.
I'm afraid to say that code taking advantage of this bug does already exist, I'm currently using it as a means to allow importing several pattern synonyms at once as a workaround for https://github.com/ghc-proposals/ghc-proposals/pull/28
The users guide states
Bundled pattern synonyms are type checked to ensure that they are of the same type as the type constructor which they are bundled with. A pattern synonym P can not be bundled with a type constructor T if P‘s type is visibly incompatible with T.
The users guide also mentions that the types in the example below are distinct for pattern synonyms. https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#typing-of-pattern-synonyms
Steps to reproduce
- Compile this module
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE EmptyDataDecls #-}
module A
( Foo
, FooPatterns(One) -- No error is generated here
) where
newtype Foo = Foo Int
-- | An empty data declaration used to export the "One" pattern
data FooPatterns
-- The commented signature causes GHC to fail with `Couldn't match expected
-- type of ‘FooPatterns’ with actual type of ‘Foo’` when exporting this pattern
-- bundled with `FooPatterns above`.
-- pattern One :: Foo
pattern One :: (a ~ Foo) => a
pattern One = Foo 1
-
Observe that no error is generated.
-
Remove the type annotation for
pattern One
-
Observe that GHC reports the following error:
A.hs:7:5-20: error:
• Pattern synonyms can only be bundled with matching type constructors
Couldn't match expected type of ‘FooPatterns’ with actual type of ‘Foo’
• In the pattern synonym: One
In the export: FooPatterns(One)
|
7 | , FooPatterns(One)
| ^^^^^^^^^^^^^^^^
Expected behavior
GHC reports the error in both cases
Environment
This behavior is present in GHC versions 8.7.20190115, 8.6.4, 8.4.4 and 8.2.2 at least.