Skip to content

Warn on ambiguous derivation

Motivation

The language extension DerivingStrateges allows you to specify how GHC derives instances. It has a strong motivating argument: there are multiple ways to derive instances with different meanings, and switching strategies can cause silent changes to the meaning of a program.

Proposal

I would like to have a warning flag that warns whenever a potentially ambiguous derivation is specified.

If no deriving extensions are enabled, then this would never produce warnings, as only stock deriving is enabled.

If GeneralizedNewtypeDeriving is enabled, then this should trigger a warning whenever a newtype has a stock-derivable class. As an example,

newtype Foo = Foo Int
  deriving (Show, ToJSON)

The deriving Show is problematic because it can pick either stock or newtype deriving strategies. The deriving ToJSON is unambiguous, because only GeneralizedNewtypeDeriving is enabled. The warning should suggest enabling DerivingStrategies and selecting one of stock or newtype, eg:

Warning: ambiguous type class derivation found in a declaration:

    newtype Foo = Foo Int
      deriving (Show, ToJSON)
                ^^^^

Show can be derived with `stock` or `newtype` strategies, with 
potentially different behavior. To resolve this warning, enable
`DerivingStrategies` language extension (if not already enabled)
and specify a strategy, like so:

    newtype Foo = Foo Int
      deriving stock Show
      deriving ToJSON

So, informally, if GHC has to pick a deriving strategy, it should issue this warning with the flag enabled.

To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information