Request for feedback: deriving strategies syntax

Ryan Scott ryan.gl.scott at gmail.com
Wed Aug 3 17:23:43 UTC 2016


That is a good question. Weirdly enough, the current behavior for how
a deriving strategy is resolved (without explicit keywords) isn't
really documented anywhere, so I attempted to figure out what GHC
currently does and documented it here [1]. I'll reproduce the
algorithm (including deriving strategies) below:

1. Look for a deriving strategy. If one is present, use that.

2. (a) If deriving an `Eq`, `Ord`, `Ix`, or `Bounded` instance for a
newtype, use the `GeneralizedNewtypeDeriving` strategy (even if the
language extension isn't enabled).

   (b) If deriving a `Read`, `Show`, `Data`, `Generic`, `Generic1`,
`Typeable`, `Traversable`, or `Lift` instance for a newtype, go to
step 3.

   (c) Otherwise, if deriving a "standard derivable class" (e.g.,
`Eq`, `Ord`, `Generic`, etc.) instance for a newtype, and
`-XGeneralizedNewtypeDeriving` is enabled, derive the class using the
`GeneralizedNewtypeDeriving` strategy.

   (d) Otherwise, if deriving an instance for a newtype and both
`-XGeneralizedNewtypeDeriving` and `-XDeriveAnyClass` are enabled,
default to `DeriveAnyClass`, but emit a warning stating the ambiguity.

   (e) Otherwise, if deriving an instance for a newtype, the datatype
and typeclass can be successfully used with
`GeneralizedNewtypeDeriving`, and `-XGeneralizedNewtypeDeriving` is
enabled, do so.

3. (a) If deriving a "standard derivable class" (e.g., `Eq`, `Ord`,
`Generic`, etc.) and the corresponding language extension is enabled
(if necessary), do so. If the language extension is not enabled, throw
an error.

   (b) Otherwise, if `-XDeriveAnyClass` is enabled, use that.

   (c) Otherwise, throw an error.

This is quite ugly, but to my knowledge this is currently what GHC
does (excluding 2(c), which is a bit that fixes a bug reported in Trac
#10598 [2]), so there shouldn't be any change in behavior from before.
This is another good reason to want deriving strategies: trying to
remember all of that is nearly impossible!

Ryan S.
-----
[1] https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/DerivingStrategies#Thederivingstrategyresolutionalgorithm
[2] https://ghc.haskell.org/trac/ghc/ticket/10598

On Wed, Aug 3, 2016 at 11:53 AM, Richard Eisenberg <eir at cis.upenn.edu> wrote:
>
>> On Aug 2, 2016, at 6:59 PM, Ryan Scott <ryan.gl.scott at gmail.com> wrote:
>> Any other questions or comments?
>>
>
> Yes, a question: What is the behavior if no keyword is given? Any change here from the status quo is quite dangerous from a backward-compatibility standpoint, but I wonder if we could start issuing warnings/errors in a few years.
>
> Richard
>


More information about the ghc-devs mailing list