Skip to content

GHC doesn't throw compilation error for some illegal instances derived from `DerivingVia` and `MultiParamTypeClasses`

Summary

In some cases, automatic derivation with DerivingVia and MultiParamTypeClasses for declaration which should fail to derive does not result in compilation error and generates an implementation that causes infinite loop.

Steps to reproduce

Preparing main.hs like the following:

{- cabal:
build-depends: base
-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE StandaloneDeriving #-}

module Main where

class Convert a b where
    convert :: a -> b

newtype NewInt = NewInt Int deriving Show

instance Convert Integer NewInt where
    convert = NewInt . fromInteger

deriving via NewInt instance Convert Double NewInt

main :: IO ()
main = print (convert (0.1 :: Double) :: NewInt) -- Freeze on execution

and executing cabal run main.hs, then GHC causes <<loop>>.

Expected behavior

The clause deriving via NewInt instance Convert Double NewInt should cause compilation error such as: Couldn't match expected type ‘Integer’ with actual type ‘Double’

Environment

  • GHC version used: 8.10.7, 9.2.5, 9.4.4
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information