DeriveLift extension (#1830)
[ghc.git] / compiler / typecheck / TcDeriv.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 Handles @deriving@ clauses on @data@ declarations.
7 -}
8
9 {-# LANGUAGE CPP #-}
10
11 module TcDeriv ( tcDeriving, DerivInfo(..), mkDerivInfos ) where
12
13 #include "HsVersions.h"
14
15 import HsSyn
16 import DynFlags
17
18 import TcRnMonad
19 import FamInst
20 import TcErrors( reportAllUnsolved )
21 import TcValidity( validDerivPred )
22 import TcClassDcl( tcMkDeclCtxt )
23 import TcEnv
24 import TcGenDeriv -- Deriv stuff
25 import TcGenGenerics
26 import InstEnv
27 import Inst
28 import FamInstEnv
29 import TcHsType
30 import TcMType
31 import TcSimplify
32 import LoadIface( loadInterfaceForName )
33 import Module( getModule )
34
35 import RnNames( extendGlobalRdrEnvRn )
36 import RnBinds
37 import RnEnv
38 import RnSource ( addTcgDUs )
39 import HscTypes
40 import Avail
41
42 import Unify( tcUnifyTy )
43 import Class
44 import Type
45 import ErrUtils
46 import DataCon
47 import Maybes
48 import RdrName
49 import Name
50 import NameEnv
51 import NameSet
52 import TyCon
53 import TcType
54 import Var
55 import VarSet
56 import PrelNames
57 import THNames ( liftClassKey )
58 import SrcLoc
59 import Util
60 import Outputable
61 import FastString
62 import Bag
63 import Pair
64
65 import Control.Monad
66 import Data.List
67
68 {-
69 ************************************************************************
70 * *
71 Overview
72 * *
73 ************************************************************************
74
75 Overall plan
76 ~~~~~~~~~~~~
77 1. Convert the decls (i.e. data/newtype deriving clauses,
78 plus standalone deriving) to [EarlyDerivSpec]
79
80 2. Infer the missing contexts for the InferTheta's
81
82 3. Add the derived bindings, generating InstInfos
83 -}
84
85 -- DerivSpec is purely local to this module
86 data DerivSpec theta = DS { ds_loc :: SrcSpan
87 , ds_name :: Name -- DFun name
88 , ds_tvs :: [TyVar]
89 , ds_theta :: theta
90 , ds_cls :: Class
91 , ds_tys :: [Type]
92 , ds_tc :: TyCon
93 , ds_tc_args :: [Type]
94 , ds_overlap :: Maybe OverlapMode
95 , ds_newtype :: Bool }
96 -- This spec implies a dfun declaration of the form
97 -- df :: forall tvs. theta => C tys
98 -- The Name is the name for the DFun we'll build
99 -- The tyvars bind all the variables in the theta
100 -- For type families, the tycon in
101 -- in ds_tys is the *family* tycon
102 -- in ds_tc, ds_tc_args is the *representation* tycon
103 -- For non-family tycons, both are the same
104
105 -- the theta is either the given and final theta, in standalone deriving,
106 -- or the not-yet-simplified list of constraints together with their origin
107
108 -- ds_newtype = True <=> Generalised Newtype Deriving (GND)
109 -- False <=> Vanilla deriving
110
111 {-
112 Example:
113
114 newtype instance T [a] = MkT (Tree a) deriving( C s )
115 ==>
116 axiom T [a] = :RTList a
117 axiom :RTList a = Tree a
118
119 DS { ds_tvs = [a,s], ds_cls = C, ds_tys = [s, T [a]]
120 , ds_tc = :RTList, ds_tc_args = [a]
121 , ds_newtype = True }
122 -}
123
124 type DerivContext = Maybe ThetaType
125 -- Nothing <=> Vanilla deriving; infer the context of the instance decl
126 -- Just theta <=> Standalone deriving: context supplied by programmer
127
128 data PredOrigin = PredOrigin PredType CtOrigin
129 type ThetaOrigin = [PredOrigin]
130
131 mkPredOrigin :: CtOrigin -> PredType -> PredOrigin
132 mkPredOrigin origin pred = PredOrigin pred origin
133
134 mkThetaOrigin :: CtOrigin -> ThetaType -> ThetaOrigin
135 mkThetaOrigin origin = map (mkPredOrigin origin)
136
137 data EarlyDerivSpec = InferTheta (DerivSpec ThetaOrigin)
138 | GivenTheta (DerivSpec ThetaType)
139 -- InferTheta ds => the context for the instance should be inferred
140 -- In this case ds_theta is the list of all the constraints
141 -- needed, such as (Eq [a], Eq a), together with a suitable CtLoc
142 -- to get good error messages.
143 -- The inference process is to reduce this to a simpler form (e.g.
144 -- Eq a)
145 --
146 -- GivenTheta ds => the exact context for the instance is supplied
147 -- by the programmer; it is ds_theta
148
149 forgetTheta :: EarlyDerivSpec -> DerivSpec ()
150 forgetTheta (InferTheta spec) = spec { ds_theta = () }
151 forgetTheta (GivenTheta spec) = spec { ds_theta = () }
152
153 earlyDSLoc :: EarlyDerivSpec -> SrcSpan
154 earlyDSLoc (InferTheta spec) = ds_loc spec
155 earlyDSLoc (GivenTheta spec) = ds_loc spec
156
157 splitEarlyDerivSpec :: [EarlyDerivSpec] -> ([DerivSpec ThetaOrigin], [DerivSpec ThetaType])
158 splitEarlyDerivSpec [] = ([],[])
159 splitEarlyDerivSpec (InferTheta spec : specs) =
160 case splitEarlyDerivSpec specs of (is, gs) -> (spec : is, gs)
161 splitEarlyDerivSpec (GivenTheta spec : specs) =
162 case splitEarlyDerivSpec specs of (is, gs) -> (is, spec : gs)
163
164 pprDerivSpec :: Outputable theta => DerivSpec theta -> SDoc
165 pprDerivSpec (DS { ds_loc = l, ds_name = n, ds_tvs = tvs,
166 ds_cls = c, ds_tys = tys, ds_theta = rhs })
167 = parens (hsep [ppr l, ppr n, ppr tvs, ppr c, ppr tys]
168 <+> equals <+> ppr rhs)
169
170 instance Outputable theta => Outputable (DerivSpec theta) where
171 ppr = pprDerivSpec
172
173 instance Outputable EarlyDerivSpec where
174 ppr (InferTheta spec) = ppr spec <+> ptext (sLit "(Infer)")
175 ppr (GivenTheta spec) = ppr spec <+> ptext (sLit "(Given)")
176
177 instance Outputable PredOrigin where
178 ppr (PredOrigin ty _) = ppr ty -- The origin is not so interesting when debugging
179
180 {-
181 Inferring missing contexts
182 ~~~~~~~~~~~~~~~~~~~~~~~~~~
183 Consider
184
185 data T a b = C1 (Foo a) (Bar b)
186 | C2 Int (T b a)
187 | C3 (T a a)
188 deriving (Eq)
189
190 [NOTE: See end of these comments for what to do with
191 data (C a, D b) => T a b = ...
192 ]
193
194 We want to come up with an instance declaration of the form
195
196 instance (Ping a, Pong b, ...) => Eq (T a b) where
197 x == y = ...
198
199 It is pretty easy, albeit tedious, to fill in the code "...". The
200 trick is to figure out what the context for the instance decl is,
201 namely @Ping@, @Pong@ and friends.
202
203 Let's call the context reqd for the T instance of class C at types
204 (a,b, ...) C (T a b). Thus:
205
206 Eq (T a b) = (Ping a, Pong b, ...)
207
208 Now we can get a (recursive) equation from the @data@ decl:
209
210 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
211 u Eq (T b a) u Eq Int -- From C2
212 u Eq (T a a) -- From C3
213
214 Foo and Bar may have explicit instances for @Eq@, in which case we can
215 just substitute for them. Alternatively, either or both may have
216 their @Eq@ instances given by @deriving@ clauses, in which case they
217 form part of the system of equations.
218
219 Now all we need do is simplify and solve the equations, iterating to
220 find the least fixpoint. Notice that the order of the arguments can
221 switch around, as here in the recursive calls to T.
222
223 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
224
225 We start with:
226
227 Eq (T a b) = {} -- The empty set
228
229 Next iteration:
230 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
231 u Eq (T b a) u Eq Int -- From C2
232 u Eq (T a a) -- From C3
233
234 After simplification:
235 = Eq a u Ping b u {} u {} u {}
236 = Eq a u Ping b
237
238 Next iteration:
239
240 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
241 u Eq (T b a) u Eq Int -- From C2
242 u Eq (T a a) -- From C3
243
244 After simplification:
245 = Eq a u Ping b
246 u (Eq b u Ping a)
247 u (Eq a u Ping a)
248
249 = Eq a u Ping b u Eq b u Ping a
250
251 The next iteration gives the same result, so this is the fixpoint. We
252 need to make a canonical form of the RHS to ensure convergence. We do
253 this by simplifying the RHS to a form in which
254
255 - the classes constrain only tyvars
256 - the list is sorted by tyvar (major key) and then class (minor key)
257 - no duplicates, of course
258
259 So, here are the synonyms for the ``equation'' structures:
260
261
262 Note [Data decl contexts]
263 ~~~~~~~~~~~~~~~~~~~~~~~~~
264 Consider
265
266 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
267
268 We will need an instance decl like:
269
270 instance (Read a, RealFloat a) => Read (Complex a) where
271 ...
272
273 The RealFloat in the context is because the read method for Complex is bound
274 to construct a Complex, and doing that requires that the argument type is
275 in RealFloat.
276
277 But this ain't true for Show, Eq, Ord, etc, since they don't construct
278 a Complex; they only take them apart.
279
280 Our approach: identify the offending classes, and add the data type
281 context to the instance decl. The "offending classes" are
282
283 Read, Enum?
284
285 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
286 pattern matching against a constructor from a data type with a context
287 gives rise to the constraints for that context -- or at least the thinned
288 version. So now all classes are "offending".
289
290 Note [Newtype deriving]
291 ~~~~~~~~~~~~~~~~~~~~~~~
292 Consider this:
293 class C a b
294 instance C [a] Char
295 newtype T = T Char deriving( C [a] )
296
297 Notice the free 'a' in the deriving. We have to fill this out to
298 newtype T = T Char deriving( forall a. C [a] )
299
300 And then translate it to:
301 instance C [a] Char => C [a] T where ...
302
303
304 Note [Newtype deriving superclasses]
305 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
306 (See also Trac #1220 for an interesting exchange on newtype
307 deriving and superclasses.)
308
309 The 'tys' here come from the partial application in the deriving
310 clause. The last arg is the new instance type.
311
312 We must pass the superclasses; the newtype might be an instance
313 of them in a different way than the representation type
314 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
315 Then the Show instance is not done via Coercible; it shows
316 Foo 3 as "Foo 3"
317 The Num instance is derived via Coercible, but the Show superclass
318 dictionary must the Show instance for Foo, *not* the Show dictionary
319 gotten from the Num dictionary. So we must build a whole new dictionary
320 not just use the Num one. The instance we want is something like:
321 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
322 (+) = ((+)@a)
323 ...etc...
324 There may be a coercion needed which we get from the tycon for the newtype
325 when the dict is constructed in TcInstDcls.tcInstDecl2
326
327
328 Note [Unused constructors and deriving clauses]
329 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
330 See Trac #3221. Consider
331 data T = T1 | T2 deriving( Show )
332 Are T1 and T2 unused? Well, no: the deriving clause expands to mention
333 both of them. So we gather defs/uses from deriving just like anything else.
334
335 -}
336
337 -- | Stuff needed to process a `deriving` clause
338 data DerivInfo = DerivInfo { di_rep_tc :: TyCon
339 -- ^ The data tycon for normal datatypes,
340 -- or the *representation* tycon for data families
341 , di_preds :: [LHsType Name]
342 , di_ctxt :: SDoc -- ^ error context
343 }
344
345 -- | Extract `deriving` clauses of proper data type (skips data families)
346 mkDerivInfos :: [TyClGroup Name] -> TcM [DerivInfo]
347 mkDerivInfos tycls = concatMapM mk_derivs tycls
348 where
349 mk_derivs (TyClGroup { group_tyclds = decls })
350 = concatMapM (mk_deriv . unLoc) decls
351
352 mk_deriv decl@(DataDecl { tcdLName = L _ data_name
353 , tcdDataDefn =
354 HsDataDefn { dd_derivs = Just (L _ preds) } })
355 = do { tycon <- tcLookupTyCon data_name
356 ; return [DerivInfo { di_rep_tc = tycon, di_preds = preds
357 , di_ctxt = tcMkDeclCtxt decl }] }
358 mk_deriv _ = return []
359
360 {-
361
362 ************************************************************************
363 * *
364 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
365 * *
366 ************************************************************************
367 -}
368
369 tcDeriving :: [DerivInfo] -- All `deriving` clauses
370 -> [LDerivDecl Name] -- All stand-alone deriving declarations
371 -> TcM (TcGblEnv, Bag (InstInfo Name), HsValBinds Name)
372 tcDeriving deriv_infos deriv_decls
373 = recoverM (do { g <- getGblEnv
374 ; return (g, emptyBag, emptyValBindsOut)}) $
375 do { -- Fish the "deriving"-related information out of the TcEnv
376 -- And make the necessary "equations".
377 is_boot <- tcIsHsBootOrSig
378 ; traceTc "tcDeriving" (ppr is_boot)
379
380 ; early_specs <- makeDerivSpecs is_boot deriv_infos deriv_decls
381 ; traceTc "tcDeriving 1" (ppr early_specs)
382
383 -- for each type, determine the auxliary declarations that are common
384 -- to multiple derivations involving that type (e.g. Generic and
385 -- Generic1 should use the same TcGenGenerics.MetaTyCons)
386 ; (commonAuxs, auxDerivStuff) <- commonAuxiliaries $ map forgetTheta early_specs
387
388 ; let (infer_specs, given_specs) = splitEarlyDerivSpec early_specs
389 ; insts1 <- mapM (genInst commonAuxs) given_specs
390
391 -- the stand-alone derived instances (@insts1@) are used when inferring
392 -- the contexts for "deriving" clauses' instances (@infer_specs@)
393 ; final_specs <- extendLocalInstEnv (map (iSpec . fstOf3) insts1) $
394 inferInstanceContexts infer_specs
395
396 ; insts2 <- mapM (genInst commonAuxs) final_specs
397
398 ; let (inst_infos, deriv_stuff, maybe_fvs) = unzip3 (insts1 ++ insts2)
399 ; loc <- getSrcSpanM
400 ; let (binds, newTyCons, famInsts, extraInstances) =
401 genAuxBinds loc (unionManyBags (auxDerivStuff : deriv_stuff))
402
403 ; dflags <- getDynFlags
404
405 ; (inst_info, rn_binds, rn_dus) <-
406 renameDeriv is_boot (inst_infos ++ (bagToList extraInstances)) binds
407
408 ; unless (isEmptyBag inst_info) $
409 liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
410 (ddump_deriving inst_info rn_binds newTyCons famInsts))
411
412 ; let all_tycons = map ATyCon (bagToList newTyCons)
413 ; gbl_env <- tcExtendGlobalEnv all_tycons $
414 tcExtendGlobalEnvImplicit (concatMap implicitTyThings all_tycons) $
415 tcExtendLocalFamInstEnv (bagToList famInsts) $
416 tcExtendLocalInstEnv (map iSpec (bagToList inst_info)) getGblEnv
417 ; let all_dus = rn_dus `plusDU` usesOnly (mkFVs $ catMaybes maybe_fvs)
418 ; return (addTcgDUs gbl_env all_dus, inst_info, rn_binds) }
419 where
420 ddump_deriving :: Bag (InstInfo Name) -> HsValBinds Name
421 -> Bag TyCon -- ^ Empty data constructors
422 -> Bag FamInst -- ^ Rep type family instances
423 -> SDoc
424 ddump_deriving inst_infos extra_binds repMetaTys repFamInsts
425 = hang (ptext (sLit "Derived instances:"))
426 2 (vcat (map (\i -> pprInstInfoDetails i $$ text "") (bagToList inst_infos))
427 $$ ppr extra_binds)
428 $$ hangP "Generic representation:" (
429 hangP "Generated datatypes for meta-information:"
430 (vcat (map ppr (bagToList repMetaTys)))
431 $$ hangP "Representation types:"
432 (vcat (map pprRepTy (bagToList repFamInsts))))
433
434 hangP s x = text "" $$ hang (ptext (sLit s)) 2 x
435
436 -- Prints the representable type family instance
437 pprRepTy :: FamInst -> SDoc
438 pprRepTy fi@(FamInst { fi_tys = lhs })
439 = ptext (sLit "type") <+> ppr (mkTyConApp (famInstTyCon fi) lhs) <+>
440 equals <+> ppr rhs
441 where rhs = famInstRHS fi
442
443 -- As of 24 April 2012, this only shares MetaTyCons between derivations of
444 -- Generic and Generic1; thus the types and logic are quite simple.
445 type CommonAuxiliary = MetaTyCons
446 type CommonAuxiliaries = NameEnv CommonAuxiliary
447
448 commonAuxiliaries :: [DerivSpec ()] -> TcM (CommonAuxiliaries, BagDerivStuff)
449 commonAuxiliaries = foldM snoc (emptyNameEnv, emptyBag) where
450 snoc acc@(cas, stuff) (DS {ds_name = nm, ds_cls = cls, ds_tc = rep_tycon})
451 | getUnique cls `elem` [genClassKey, gen1ClassKey] =
452 extendComAux $ genGenericMetaTyCons rep_tycon (nameModule nm)
453 | otherwise = return acc
454 where extendComAux m -- don't run m if its already in the accumulator
455 | elemNameEnv (tyConName rep_tycon) cas = return acc
456 | otherwise = do (ca, new_stuff) <- m
457 return ( extendNameEnv cas (tyConName rep_tycon) ca
458 , stuff `unionBags` new_stuff)
459
460 renameDeriv :: Bool
461 -> [InstInfo RdrName]
462 -> Bag (LHsBind RdrName, LSig RdrName)
463 -> TcM (Bag (InstInfo Name), HsValBinds Name, DefUses)
464 renameDeriv is_boot inst_infos bagBinds
465 | is_boot -- If we are compiling a hs-boot file, don't generate any derived bindings
466 -- The inst-info bindings will all be empty, but it's easier to
467 -- just use rn_inst_info to change the type appropriately
468 = do { (rn_inst_infos, fvs) <- mapAndUnzipM rn_inst_info inst_infos
469 ; return ( listToBag rn_inst_infos
470 , emptyValBindsOut, usesOnly (plusFVs fvs)) }
471
472 | otherwise
473 = discardWarnings $ -- Discard warnings about unused bindings etc
474 setXOptM Opt_EmptyCase $ -- Derived decls (for empty types) can have
475 -- case x of {}
476 setXOptM Opt_ScopedTypeVariables $ -- Derived decls (for newtype-deriving) can
477 setXOptM Opt_KindSignatures $ -- used ScopedTypeVariables & KindSignatures
478 do {
479 -- Bring the extra deriving stuff into scope
480 -- before renaming the instances themselves
481 ; (aux_binds, aux_sigs) <- mapAndUnzipBagM return bagBinds
482 ; let aux_val_binds = ValBindsIn aux_binds (bagToList aux_sigs)
483 ; rn_aux_lhs <- rnTopBindsLHS emptyFsEnv aux_val_binds
484 ; let bndrs = collectHsValBinders rn_aux_lhs
485 ; envs <- extendGlobalRdrEnvRn (map Avail bndrs) emptyFsEnv ;
486 ; setEnvs envs $
487 do { (rn_aux, dus_aux) <- rnValBindsRHS (TopSigCtxt (mkNameSet bndrs)) rn_aux_lhs
488 ; (rn_inst_infos, fvs_insts) <- mapAndUnzipM rn_inst_info inst_infos
489 ; return (listToBag rn_inst_infos, rn_aux,
490 dus_aux `plusDU` usesOnly (plusFVs fvs_insts)) } }
491
492 where
493 rn_inst_info :: InstInfo RdrName -> TcM (InstInfo Name, FreeVars)
494 rn_inst_info
495 inst_info@(InstInfo { iSpec = inst
496 , iBinds = InstBindings
497 { ib_binds = binds
498 , ib_tyvars = tyvars
499 , ib_pragmas = sigs
500 , ib_extensions = exts -- Only for type-checking
501 , ib_derived = sa } })
502 = ASSERT( null sigs )
503 bindLocalNamesFV tyvars $
504 do { (rn_binds,_, fvs) <- rnMethodBinds False (is_cls_nm inst) [] binds []
505 ; let binds' = InstBindings { ib_binds = rn_binds
506 , ib_tyvars = tyvars
507 , ib_pragmas = []
508 , ib_extensions = exts
509 , ib_derived = sa }
510 ; return (inst_info { iBinds = binds' }, fvs) }
511
512 {-
513 Note [Newtype deriving and unused constructors]
514 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
515 Consider this (see Trac #1954):
516
517 module Bug(P) where
518 newtype P a = MkP (IO a) deriving Monad
519
520 If you compile with -fwarn-unused-binds you do not expect the warning
521 "Defined but not used: data consructor MkP". Yet the newtype deriving
522 code does not explicitly mention MkP, but it should behave as if you
523 had written
524 instance Monad P where
525 return x = MkP (return x)
526 ...etc...
527
528 So we want to signal a user of the data constructor 'MkP'.
529 This is the reason behind the (Maybe Name) part of the return type
530 of genInst.
531
532 Note [Why we don't pass rep_tc into deriveTyData]
533 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
534 Down in the bowels of mkEqnHelp, we need to convert the fam_tc back into
535 the rep_tc by means of a lookup. And yet we have the rep_tc right here!
536 Why look it up again? Answer: it's just easier this way.
537 We drop some number of arguments from the end of the datatype definition
538 in deriveTyData. The arguments are dropped from the fam_tc.
539 This action may drop a *different* number of arguments
540 passed to the rep_tc, depending on how many free variables, etc., the
541 dropped patterns have.
542
543 Also, this technique carries over the kind substitution from deriveTyData
544 nicely.
545
546 ************************************************************************
547 * *
548 From HsSyn to DerivSpec
549 * *
550 ************************************************************************
551
552 @makeDerivSpecs@ fishes around to find the info about needed derived instances.
553 -}
554
555 makeDerivSpecs :: Bool
556 -> [DerivInfo]
557 -> [LDerivDecl Name]
558 -> TcM [EarlyDerivSpec]
559 makeDerivSpecs is_boot deriv_infos deriv_decls
560 = do { eqns1 <- concatMapM (recoverM (return []) . deriveDerivInfo) deriv_infos
561 ; eqns2 <- concatMapM (recoverM (return []) . deriveStandalone) deriv_decls
562 ; let eqns = eqns1 ++ eqns2
563
564 ; if is_boot then -- No 'deriving' at all in hs-boot files
565 do { unless (null eqns) (add_deriv_err (head eqns))
566 ; return [] }
567 else return eqns }
568 where
569 add_deriv_err eqn
570 = setSrcSpan (earlyDSLoc eqn) $
571 addErr (hang (ptext (sLit "Deriving not permitted in hs-boot file"))
572 2 (ptext (sLit "Use an instance declaration instead")))
573
574 ------------------------------------------------------------------
575 -- | Process a `deriving` clause
576 deriveDerivInfo :: DerivInfo -> TcM [EarlyDerivSpec]
577 deriveDerivInfo (DerivInfo { di_rep_tc = rep_tc, di_preds = preds
578 , di_ctxt = err_ctxt })
579 = addErrCtxt err_ctxt $
580 concatMapM (deriveTyData tvs tc tys) preds
581 where
582 tvs = tyConTyVars rep_tc
583 (tc, tys) = case tyConFamInstSig_maybe rep_tc of
584 -- data family:
585 Just (fam_tc, pats, _) -> (fam_tc, pats)
586 -- NB: deriveTyData wants the *user-specified*
587 -- name. See Note [Why we don't pass rep_tc into deriveTyData]
588
589 _ -> (rep_tc, mkTyVarTys tvs) -- datatype
590
591 ------------------------------------------------------------------
592 deriveStandalone :: LDerivDecl Name -> TcM [EarlyDerivSpec]
593 -- Standalone deriving declarations
594 -- e.g. deriving instance Show a => Show (T a)
595 -- Rather like tcLocalInstDecl
596 deriveStandalone (L loc (DerivDecl deriv_ty overlap_mode))
597 = setSrcSpan loc $
598 addErrCtxt (standaloneCtxt deriv_ty) $
599 do { traceTc "Standalone deriving decl for" (ppr deriv_ty)
600 ; (tvs, theta, cls, inst_tys) <- tcHsInstHead TcType.InstDeclCtxt deriv_ty
601 ; traceTc "Standalone deriving;" $ vcat
602 [ text "tvs:" <+> ppr tvs
603 , text "theta:" <+> ppr theta
604 , text "cls:" <+> ppr cls
605 , text "tys:" <+> ppr inst_tys ]
606 -- C.f. TcInstDcls.tcLocalInstDecl1
607 ; checkTc (not (null inst_tys)) derivingNullaryErr
608
609 ; let cls_tys = take (length inst_tys - 1) inst_tys
610 inst_ty = last inst_tys
611 ; traceTc "Standalone deriving:" $ vcat
612 [ text "class:" <+> ppr cls
613 , text "class types:" <+> ppr cls_tys
614 , text "type:" <+> ppr inst_ty ]
615
616 ; case tcSplitTyConApp_maybe inst_ty of
617 Just (tc, tc_args)
618 | className cls == typeableClassName
619 -> do warnUselessTypeable
620 return []
621
622 | isAlgTyCon tc || isDataFamilyTyCon tc -- All other classes
623 -> do { spec <- mkEqnHelp (fmap unLoc overlap_mode)
624 tvs cls cls_tys tc tc_args (Just theta)
625 ; return [spec] }
626
627 _ -> -- Complain about functions, primitive types, etc,
628 failWithTc $ derivingThingErr False cls cls_tys inst_ty $
629 ptext (sLit "The last argument of the instance must be a data or newtype application")
630 }
631
632
633 warnUselessTypeable :: TcM ()
634 warnUselessTypeable
635 = do { warn <- woptM Opt_WarnDerivingTypeable
636 ; when warn $ addWarnTc
637 $ ptext (sLit "Deriving") <+> quotes (ppr typeableClassName) <+>
638 ptext (sLit "has no effect: all types now auto-derive Typeable") }
639
640 ------------------------------------------------------------------
641 deriveTyData :: [TyVar] -> TyCon -> [Type] -- LHS of data or data instance
642 -- Can be a data instance, hence [Type] args
643 -> LHsType Name -- The deriving predicate
644 -> TcM [EarlyDerivSpec]
645 -- The deriving clause of a data or newtype declaration
646 -- I.e. not standalone deriving
647 deriveTyData tvs tc tc_args (L loc deriv_pred)
648 = setSrcSpan loc $ -- Use the location of the 'deriving' item
649 do { (deriv_tvs, cls, cls_tys, cls_arg_kind)
650 <- tcExtendTyVarEnv tvs $
651 tcHsDeriv deriv_pred
652 -- Deriving preds may (now) mention
653 -- the type variables for the type constructor, hence tcExtendTyVarenv
654 -- The "deriv_pred" is a LHsType to take account of the fact that for
655 -- newtype deriving we allow deriving (forall a. C [a]).
656
657 -- Typeable is special, because Typeable :: forall k. k -> Constraint
658 -- so the argument kind 'k' is not decomposable by splitKindFunTys
659 -- as is the case for all other derivable type classes
660 ; if className cls == typeableClassName
661 then do warnUselessTypeable
662 return []
663 else
664
665 do { -- Given data T a b c = ... deriving( C d ),
666 -- we want to drop type variables from T so that (C d (T a)) is well-kinded
667 let (arg_kinds, _) = splitKindFunTys cls_arg_kind
668 n_args_to_drop = length arg_kinds
669 n_args_to_keep = tyConArity tc - n_args_to_drop
670 (tc_args_to_keep, args_to_drop)
671 = splitAt n_args_to_keep tc_args
672 inst_ty_kind = typeKind (mkTyConApp tc tc_args_to_keep)
673 dropped_tvs = tyVarsOfTypes args_to_drop
674
675 -- Match up the kinds, and apply the resulting kind substitution
676 -- to the types. See Note [Unify kinds in deriving]
677 -- We are assuming the tycon tyvars and the class tyvars are distinct
678 mb_match = tcUnifyTy inst_ty_kind cls_arg_kind
679 Just kind_subst = mb_match
680 (univ_kvs, univ_tvs) = partition isKindVar $ varSetElems $
681 mkVarSet deriv_tvs `unionVarSet`
682 tyVarsOfTypes tc_args_to_keep
683 univ_kvs' = filter (`notElemTvSubst` kind_subst) univ_kvs
684 (subst', univ_tvs') = mapAccumL substTyVarBndr kind_subst univ_tvs
685 final_tc_args = substTys subst' tc_args_to_keep
686 final_cls_tys = substTys subst' cls_tys
687
688 ; traceTc "derivTyData1" (vcat [ pprTvBndrs tvs, ppr tc, ppr tc_args, ppr deriv_pred
689 , pprTvBndrs (varSetElems $ tyVarsOfTypes tc_args)
690 , ppr n_args_to_keep, ppr n_args_to_drop
691 , ppr inst_ty_kind, ppr cls_arg_kind, ppr mb_match
692 , ppr final_tc_args, ppr final_cls_tys ])
693
694 -- Check that the result really is well-kinded
695 ; checkTc (n_args_to_keep >= 0 && isJust mb_match)
696 (derivingKindErr tc cls cls_tys cls_arg_kind)
697
698 ; traceTc "derivTyData2" (vcat [ ppr univ_tvs ])
699
700 ; checkTc (allDistinctTyVars args_to_drop && -- (a) and (b)
701 not (any (`elemVarSet` dropped_tvs) univ_tvs)) -- (c)
702 (derivingEtaErr cls final_cls_tys (mkTyConApp tc final_tc_args))
703 -- Check that
704 -- (a) The args to drop are all type variables; eg reject:
705 -- data instance T a Int = .... deriving( Monad )
706 -- (b) The args to drop are all *distinct* type variables; eg reject:
707 -- class C (a :: * -> * -> *) where ...
708 -- data instance T a a = ... deriving( C )
709 -- (c) The type class args, or remaining tycon args,
710 -- do not mention any of the dropped type variables
711 -- newtype T a s = ... deriving( ST s )
712 -- newtype K a a = ... deriving( Monad )
713
714 ; spec <- mkEqnHelp Nothing (univ_kvs' ++ univ_tvs')
715 cls final_cls_tys tc final_tc_args Nothing
716 ; return [spec] } }
717
718
719 {-
720 Note [Unify kinds in deriving]
721 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
722 Consider (Trac #8534)
723 data T a b = MkT a deriving( Functor )
724 -- where Functor :: (*->*) -> Constraint
725
726 So T :: forall k. * -> k -> *. We want to get
727 instance Functor (T * (a:*)) where ...
728 Notice the '*' argument to T.
729
730 Moreover, as well as instantiating T's kind arguments, we may need to instantiate
731 C's kind args. Consider (Trac #8865):
732 newtype T a b = MkT (Either a b) deriving( Category )
733 where
734 Category :: forall k. (k -> k -> *) -> Constraint
735 We need to generate the instance
736 instance Category * (Either a) where ...
737 Notice the '*' argument to Category.
738
739 So we need to
740 * drop arguments from (T a b) to match the number of
741 arrows in the (last argument of the) class;
742 * and then *unify* kind of the remaining type against the
743 expected kind, to figure out how to instantiate C's and T's
744 kind arguments.
745
746 In the two examples,
747 * we unify kind-of( T k (a:k) ) ~ kind-of( Functor )
748 i.e. (k -> *) ~ (* -> *) to find k:=*.
749 yielding k:=*
750
751 * we unify kind-of( Either ) ~ kind-of( Category )
752 i.e. (* -> * -> *) ~ (k -> k -> k)
753 yielding k:=*
754
755 Now we get a kind substitution. We then need to:
756
757 1. Remove the substituted-out kind variables from the quantified kind vars
758
759 2. Apply the substitution to the kinds of quantified *type* vars
760 (and extend the substitution to reflect this change)
761
762 3. Apply that extended substitution to the non-dropped args (types and
763 kinds) of the type and class
764
765 Forgetting step (2) caused Trac #8893:
766 data V a = V [a] deriving Functor
767 data P (x::k->*) (a:k) = P (x a) deriving Functor
768 data C (x::k->*) (a:k) = C (V (P x a)) deriving Functor
769
770 When deriving Functor for P, we unify k to *, but we then want
771 an instance $df :: forall (x:*->*). Functor x => Functor (P * (x:*->*))
772 and similarly for C. Notice the modified kind of x, both at binding
773 and occurrence sites.
774 -}
775
776 mkEqnHelp :: Maybe OverlapMode
777 -> [TyVar]
778 -> Class -> [Type]
779 -> TyCon -> [Type]
780 -> DerivContext -- Just => context supplied (standalone deriving)
781 -- Nothing => context inferred (deriving on data decl)
782 -> TcRn EarlyDerivSpec
783 -- Make the EarlyDerivSpec for an instance
784 -- forall tvs. theta => cls (tys ++ [ty])
785 -- where the 'theta' is optional (that's the Maybe part)
786 -- Assumes that this declaration is well-kinded
787
788 mkEqnHelp overlap_mode tvs cls cls_tys tycon tc_args mtheta
789 = do { -- Find the instance of a data family
790 -- Note [Looking up family instances for deriving]
791 fam_envs <- tcGetFamInstEnvs
792 ; let (rep_tc, rep_tc_args, _co) = tcLookupDataFamInst fam_envs tycon tc_args
793
794 -- If it's still a data family, the lookup failed; i.e no instance exists
795 ; when (isDataFamilyTyCon rep_tc)
796 (bale_out (ptext (sLit "No family instance for") <+> quotes (pprTypeApp tycon tc_args)))
797
798 -- For standalone deriving (mtheta /= Nothing),
799 -- check that all the data constructors are in scope.
800 ; rdr_env <- getGlobalRdrEnv
801 ; let data_con_names = map dataConName (tyConDataCons rep_tc)
802 hidden_data_cons = not (isWiredInName (tyConName rep_tc)) &&
803 (isAbstractTyCon rep_tc ||
804 any not_in_scope data_con_names)
805 not_in_scope dc = null (lookupGRE_Name rdr_env dc)
806
807 -- Make a Qual RdrName that will do for each DataCon
808 -- so we can report it as used (Trac #7969)
809 data_con_rdrs = [ greUsedRdrName gre
810 | dc_name <- data_con_names
811 , gre : _ <- [lookupGRE_Name rdr_env dc_name]
812 , not (isLocalGRE gre) ]
813
814 ; addUsedRdrNames data_con_rdrs
815 ; unless (isNothing mtheta || not hidden_data_cons)
816 (bale_out (derivingHiddenErr tycon))
817
818 ; dflags <- getDynFlags
819 ; if isDataTyCon rep_tc then
820 mkDataTypeEqn dflags overlap_mode tvs cls cls_tys
821 tycon tc_args rep_tc rep_tc_args mtheta
822 else
823 mkNewTypeEqn dflags overlap_mode tvs cls cls_tys
824 tycon tc_args rep_tc rep_tc_args mtheta }
825 where
826 bale_out msg = failWithTc (derivingThingErr False cls cls_tys (mkTyConApp tycon tc_args) msg)
827
828 {-
829 Note [Looking up family instances for deriving]
830 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
831 tcLookupFamInstExact is an auxiliary lookup wrapper which requires
832 that looked-up family instances exist. If called with a vanilla
833 tycon, the old type application is simply returned.
834
835 If we have
836 data instance F () = ... deriving Eq
837 data instance F () = ... deriving Eq
838 then tcLookupFamInstExact will be confused by the two matches;
839 but that can't happen because tcInstDecls1 doesn't call tcDeriving
840 if there are any overlaps.
841
842 There are two other things that might go wrong with the lookup.
843 First, we might see a standalone deriving clause
844 deriving Eq (F ())
845 when there is no data instance F () in scope.
846
847 Note that it's OK to have
848 data instance F [a] = ...
849 deriving Eq (F [(a,b)])
850 where the match is not exact; the same holds for ordinary data types
851 with standalone deriving declarations.
852
853 Note [Deriving, type families, and partial applications]
854 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
855 When there are no type families, it's quite easy:
856
857 newtype S a = MkS [a]
858 -- :CoS :: S ~ [] -- Eta-reduced
859
860 instance Eq [a] => Eq (S a) -- by coercion sym (Eq (:CoS a)) : Eq [a] ~ Eq (S a)
861 instance Monad [] => Monad S -- by coercion sym (Monad :CoS) : Monad [] ~ Monad S
862
863 When type familes are involved it's trickier:
864
865 data family T a b
866 newtype instance T Int a = MkT [a] deriving( Eq, Monad )
867 -- :RT is the representation type for (T Int a)
868 -- :Co:RT :: :RT ~ [] -- Eta-reduced!
869 -- :CoF:RT a :: T Int a ~ :RT a -- Also eta-reduced!
870
871 instance Eq [a] => Eq (T Int a) -- easy by coercion
872 -- d1 :: Eq [a]
873 -- d2 :: Eq (T Int a) = d1 |> Eq (sym (:Co:RT a ; :coF:RT a))
874
875 instance Monad [] => Monad (T Int) -- only if we can eta reduce???
876 -- d1 :: Monad []
877 -- d2 :: Monad (T Int) = d1 |> Monad (sym (:Co:RT ; :coF:RT))
878
879 Note the need for the eta-reduced rule axioms. After all, we can
880 write it out
881 instance Monad [] => Monad (T Int) -- only if we can eta reduce???
882 return x = MkT [x]
883 ... etc ...
884
885 See Note [Eta reduction for data family axioms] in TcInstDcls.
886
887
888 ************************************************************************
889 * *
890 Deriving data types
891 * *
892 ************************************************************************
893 -}
894
895 mkDataTypeEqn :: DynFlags
896 -> Maybe OverlapMode
897 -> [Var] -- Universally quantified type variables in the instance
898 -> Class -- Class for which we need to derive an instance
899 -> [Type] -- Other parameters to the class except the last
900 -> TyCon -- Type constructor for which the instance is requested
901 -- (last parameter to the type class)
902 -> [Type] -- Parameters to the type constructor
903 -> TyCon -- rep of the above (for type families)
904 -> [Type] -- rep of the above
905 -> DerivContext -- Context of the instance, for standalone deriving
906 -> TcRn EarlyDerivSpec -- Return 'Nothing' if error
907
908 mkDataTypeEqn dflags overlap_mode tvs cls cls_tys
909 tycon tc_args rep_tc rep_tc_args mtheta
910 = case checkSideConditions dflags mtheta cls cls_tys rep_tc rep_tc_args of
911 -- NB: pass the *representation* tycon to checkSideConditions
912 NonDerivableClass msg -> bale_out (nonStdErr cls $$ msg)
913 DerivableClassError msg -> bale_out msg
914 CanDerive -> go_for_it
915 DerivableViaInstance -> go_for_it
916 where
917 go_for_it = mk_data_eqn overlap_mode tvs cls tycon tc_args rep_tc rep_tc_args mtheta
918 bale_out msg = failWithTc (derivingThingErr False cls cls_tys (mkTyConApp tycon tc_args) msg)
919
920 mk_data_eqn :: Maybe OverlapMode -> [TyVar] -> Class
921 -> TyCon -> [TcType] -> TyCon -> [TcType] -> DerivContext
922 -> TcM EarlyDerivSpec
923 mk_data_eqn overlap_mode tvs cls tycon tc_args rep_tc rep_tc_args mtheta
924 = do loc <- getSrcSpanM
925 dfun_name <- new_dfun_name cls tycon
926 case mtheta of
927 Nothing -> do --Infer context
928 inferred_constraints <- inferConstraints cls inst_tys rep_tc rep_tc_args
929 return $ InferTheta $ DS
930 { ds_loc = loc
931 , ds_name = dfun_name, ds_tvs = tvs
932 , ds_cls = cls, ds_tys = inst_tys
933 , ds_tc = rep_tc, ds_tc_args = rep_tc_args
934 , ds_theta = inferred_constraints
935 , ds_overlap = overlap_mode
936 , ds_newtype = False }
937 Just theta -> do -- Specified context
938 return $ GivenTheta $ DS
939 { ds_loc = loc
940 , ds_name = dfun_name, ds_tvs = tvs
941 , ds_cls = cls, ds_tys = inst_tys
942 , ds_tc = rep_tc, ds_tc_args = rep_tc_args
943 , ds_theta = theta
944 , ds_overlap = overlap_mode
945 , ds_newtype = False }
946 where
947 inst_tys = [mkTyConApp tycon tc_args]
948
949 ----------------------
950
951 inferConstraints :: Class -> [TcType]
952 -> TyCon -> [TcType]
953 -> TcM ThetaOrigin
954 -- Generate a sufficiently large set of constraints that typechecking the
955 -- generated method definitions should succeed. This set will be simplified
956 -- before being used in the instance declaration
957 inferConstraints cls inst_tys rep_tc rep_tc_args
958 | cls `hasKey` genClassKey -- Generic constraints are easy
959 = return []
960
961 | cls `hasKey` gen1ClassKey -- Gen1 needs Functor
962 = ASSERT(length rep_tc_tvs > 0) -- See Note [Getting base classes]
963 do { functorClass <- tcLookupClass functorClassName
964 ; return (con_arg_constraints (get_gen1_constraints functorClass)) }
965
966 | otherwise -- The others are a bit more complicated
967 = ASSERT2( equalLength rep_tc_tvs all_rep_tc_args, ppr cls <+> ppr rep_tc )
968 do { traceTc "inferConstraints" (vcat [ppr cls <+> ppr inst_tys, ppr arg_constraints])
969 ; return (stupid_constraints ++ extra_constraints
970 ++ sc_constraints
971 ++ arg_constraints) }
972 where
973 arg_constraints = con_arg_constraints get_std_constrained_tys
974
975 -- Constraints arising from the arguments of each constructor
976 con_arg_constraints :: (CtOrigin -> Type -> [PredOrigin]) -> [PredOrigin]
977 con_arg_constraints get_arg_constraints
978 = [ pred
979 | data_con <- tyConDataCons rep_tc
980 , (arg_n, arg_ty) <- ASSERT( isVanillaDataCon data_con )
981 zip [1..] $ -- ASSERT is precondition of dataConInstOrigArgTys
982 dataConInstOrigArgTys data_con all_rep_tc_args
983 , not (isUnLiftedType arg_ty)
984 , let orig = DerivOriginDC data_con arg_n
985 , pred <- get_arg_constraints orig arg_ty ]
986
987 -- No constraints for unlifted types
988 -- See Note [Deriving and unboxed types]
989
990 -- For functor-like classes, two things are different
991 -- (a) We recurse over argument types to generate constraints
992 -- See Functor examples in TcGenDeriv
993 -- (b) The rep_tc_args will be one short
994 is_functor_like = getUnique cls `elem` functorLikeClassKeys
995 || onlyOneAndTypeConstr inst_tys
996 onlyOneAndTypeConstr [inst_ty] = typeKind inst_ty `tcEqKind` a2a_kind
997 onlyOneAndTypeConstr _ = False
998
999 a2a_kind = mkArrowKind liftedTypeKind liftedTypeKind
1000
1001 get_gen1_constraints functor_cls orig ty
1002 = mk_functor_like_constraints orig functor_cls $
1003 get_gen1_constrained_tys last_tv ty
1004
1005 get_std_constrained_tys :: CtOrigin -> Type -> [PredOrigin]
1006 get_std_constrained_tys orig ty
1007 | is_functor_like = mk_functor_like_constraints orig cls $
1008 deepSubtypesContaining last_tv ty
1009 | otherwise = [mkPredOrigin orig (mkClassPred cls [ty])]
1010
1011 mk_functor_like_constraints :: CtOrigin -> Class -> [Type] -> [PredOrigin]
1012 -- 'cls' is Functor or Traversable etc
1013 -- For each type, generate two constraints: (cls ty, kind(ty) ~ (*->*))
1014 -- The second constraint checks that the first is well-kinded.
1015 -- Lacking that, as Trac #10561 showed, we can just generate an
1016 -- ill-kinded instance.
1017 mk_functor_like_constraints orig cls tys
1018 = [ mkPredOrigin orig pred
1019 | ty <- tys
1020 , pred <- [ mkClassPred cls [ty]
1021 , mkEqPred (typeKind ty) a2a_kind] ]
1022
1023 rep_tc_tvs = tyConTyVars rep_tc
1024 last_tv = last rep_tc_tvs
1025 all_rep_tc_args | cls `hasKey` gen1ClassKey || is_functor_like
1026 = rep_tc_args ++ [mkTyVarTy last_tv]
1027 | otherwise = rep_tc_args
1028
1029 -- Constraints arising from superclasses
1030 -- See Note [Superclasses of derived instance]
1031 sc_constraints = mkThetaOrigin DerivOrigin $
1032 substTheta (zipOpenTvSubst (classTyVars cls) inst_tys) (classSCTheta cls)
1033
1034 -- Stupid constraints
1035 stupid_constraints = mkThetaOrigin DerivOrigin $
1036 substTheta subst (tyConStupidTheta rep_tc)
1037 subst = zipTopTvSubst rep_tc_tvs all_rep_tc_args
1038
1039 -- Extra Data constraints
1040 -- The Data class (only) requires that for
1041 -- instance (...) => Data (T t1 t2)
1042 -- IF t1:*, t2:*
1043 -- THEN (Data t1, Data t2) are among the (...) constraints
1044 -- Reason: when the IF holds, we generate a method
1045 -- dataCast2 f = gcast2 f
1046 -- and we need the Data constraints to typecheck the method
1047 extra_constraints
1048 | cls `hasKey` dataClassKey
1049 , all (isLiftedTypeKind . typeKind) rep_tc_args
1050 = [mkPredOrigin DerivOrigin (mkClassPred cls [ty]) | ty <- rep_tc_args]
1051 | otherwise
1052 = []
1053
1054 {-
1055 Note [Getting base classes]
1056 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1057 Functor and Typeable are defined in package 'base', and that is not available
1058 when compiling 'ghc-prim'. So we must be careful that 'deriving' for stuff in
1059 ghc-prim does not use Functor or Typeable implicitly via these lookups.
1060
1061 Note [Deriving and unboxed types]
1062 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1063 We have some special hacks to support things like
1064 data T = MkT Int# deriving ( Show )
1065
1066 Specifically, we use TcGenDeriv.box to box the Int# into an Int
1067 (which we know how to show), and append a '#'. Parenthesis are not required
1068 for unboxed values (`MkT -3#` is a valid expression).
1069
1070 Note [Deriving any class]
1071 ~~~~~~~~~~~~~~~~~~~~~~~~~
1072 Classic uses of a deriving clause, or a standalone-deriving declaration, are
1073 for:
1074 * a built-in class like Eq or Show, for which GHC knows how to generate
1075 the instance code
1076 * a newtype, via the mechanism enabled by GeneralizedNewtypeDeriving
1077
1078 The DeriveAnyClass extension adds a third way to derive instances, based on
1079 empty instance declarations.
1080
1081 The canonical use case is in combination with GHC.Generics and default method
1082 signatures. These allow us to have instance declarations being empty, but still
1083 useful, e.g.
1084
1085 data T a = ...blah..blah... deriving( Generic )
1086 instance C a => C (T a) -- No 'where' clause
1087
1088 where C is some "random" user-defined class.
1089
1090 This boilerplate code can be replaced by the more compact
1091
1092 data T a = ...blah..blah... deriving( Generic, C )
1093
1094 if DeriveAnyClass is enabled.
1095
1096 This is not restricted to Generics; any class can be derived, simply giving
1097 rise to an empty instance.
1098
1099 Unfortunately, it is not clear how to determine the context (in case of
1100 standard deriving; in standalone deriving, the user provides the context).
1101 GHC uses the same heuristic for figuring out the class context that it uses for
1102 Eq in the case of *-kinded classes, and for Functor in the case of
1103 * -> *-kinded classes. That may not be optimal or even wrong. But in such
1104 cases, standalone deriving can still be used.
1105 -}
1106
1107 ------------------------------------------------------------------
1108 -- Check side conditions that dis-allow derivability for particular classes
1109 -- This is *apart* from the newtype-deriving mechanism
1110 --
1111 -- Here we get the representation tycon in case of family instances as it has
1112 -- the data constructors - but we need to be careful to fall back to the
1113 -- family tycon (with indexes) in error messages.
1114
1115 data DerivStatus = CanDerive -- Standard class, can derive
1116 | DerivableClassError SDoc -- Standard class, but can't do it
1117 | DerivableViaInstance -- See Note [Deriving any class]
1118 | NonDerivableClass SDoc -- Non-standard class
1119
1120 -- A "standard" class is one defined in the Haskell report which GHC knows how
1121 -- to generate code for, such as Eq, Ord, Ix, etc.
1122
1123 checkSideConditions :: DynFlags -> DerivContext -> Class -> [TcType]
1124 -> TyCon -> [Type] -- tycon and its parameters
1125 -> DerivStatus
1126 checkSideConditions dflags mtheta cls cls_tys rep_tc rep_tc_args
1127 | Just cond <- sideConditions mtheta cls
1128 = case (cond (dflags, rep_tc, rep_tc_args)) of
1129 NotValid err -> DerivableClassError err -- Class-specific error
1130 IsValid | null cls_tys -> CanDerive -- All derivable classes are unary, so
1131 -- cls_tys (the type args other than last)
1132 -- should be null
1133 | otherwise -> DerivableClassError (classArgsErr cls cls_tys) -- e.g. deriving( Eq s )
1134 | otherwise = maybe DerivableViaInstance NonDerivableClass
1135 (canDeriveAnyClass dflags rep_tc cls)
1136
1137 classArgsErr :: Class -> [Type] -> SDoc
1138 classArgsErr cls cls_tys = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "is not a class")
1139
1140 nonStdErr :: Class -> SDoc
1141 nonStdErr cls =
1142 quotes (ppr cls)
1143 <+> ptext (sLit "is not a standard derivable class (Eq, Show, etc.)")
1144
1145 sideConditions :: DerivContext -> Class -> Maybe Condition
1146 sideConditions mtheta cls
1147 | cls_key == eqClassKey = Just (cond_std `andCond` cond_args cls)
1148 | cls_key == ordClassKey = Just (cond_std `andCond` cond_args cls)
1149 | cls_key == showClassKey = Just (cond_std `andCond` cond_args cls)
1150 | cls_key == readClassKey = Just (cond_std `andCond` cond_args cls)
1151 | cls_key == enumClassKey = Just (cond_std `andCond` cond_isEnumeration)
1152 | cls_key == ixClassKey = Just (cond_std `andCond` cond_enumOrProduct cls)
1153 | cls_key == boundedClassKey = Just (cond_std `andCond` cond_enumOrProduct cls)
1154 | cls_key == dataClassKey = Just (checkFlag Opt_DeriveDataTypeable `andCond`
1155 cond_std `andCond`
1156 cond_args cls)
1157 | cls_key == functorClassKey = Just (checkFlag Opt_DeriveFunctor `andCond`
1158 cond_vanilla `andCond`
1159 cond_functorOK True False)
1160 | cls_key == foldableClassKey = Just (checkFlag Opt_DeriveFoldable `andCond`
1161 cond_vanilla `andCond`
1162 cond_functorOK False True)
1163 -- Functor/Fold/Trav works ok
1164 -- for rank-n types
1165 | cls_key == traversableClassKey = Just (checkFlag Opt_DeriveTraversable `andCond`
1166 cond_vanilla `andCond`
1167 cond_functorOK False False)
1168 | cls_key == genClassKey = Just (checkFlag Opt_DeriveGeneric `andCond`
1169 cond_vanilla `andCond`
1170 cond_RepresentableOk)
1171 | cls_key == gen1ClassKey = Just (checkFlag Opt_DeriveGeneric `andCond`
1172 cond_vanilla `andCond`
1173 cond_Representable1Ok)
1174 | cls_key == liftClassKey = Just (checkFlag Opt_DeriveLift `andCond`
1175 cond_vanilla `andCond`
1176 cond_args cls)
1177 | otherwise = Nothing
1178 where
1179 cls_key = getUnique cls
1180 cond_std = cond_stdOK mtheta False -- Vanilla data constructors, at least one,
1181 -- and monotype arguments
1182 cond_vanilla = cond_stdOK mtheta True -- Vanilla data constructors but
1183 -- allow no data cons or polytype arguments
1184
1185 type Condition = (DynFlags, TyCon, [Type]) -> Validity
1186 -- first Bool is whether or not we are allowed to derive Data and Typeable
1187 -- second Bool is whether or not we are allowed to derive Functor
1188 -- TyCon is the *representation* tycon if the data type is an indexed one
1189 -- [Type] are the type arguments to the (representation) TyCon
1190 -- Nothing => OK
1191
1192 orCond :: Condition -> Condition -> Condition
1193 orCond c1 c2 tc
1194 = case (c1 tc, c2 tc) of
1195 (IsValid, _) -> IsValid -- c1 succeeds
1196 (_, IsValid) -> IsValid -- c21 succeeds
1197 (NotValid x, NotValid y) -> NotValid (x $$ ptext (sLit " or") $$ y)
1198 -- Both fail
1199
1200 andCond :: Condition -> Condition -> Condition
1201 andCond c1 c2 tc = c1 tc `andValid` c2 tc
1202
1203 cond_stdOK :: DerivContext -- Says whether this is standalone deriving or not;
1204 -- if standalone, we just say "yes, go for it"
1205 -> Bool -- True <=> permissive: allow higher rank
1206 -- args and no data constructors
1207 -> Condition
1208 cond_stdOK (Just _) _ _
1209 = IsValid -- Don't check these conservative conditions for
1210 -- standalone deriving; just generate the code
1211 -- and let the typechecker handle the result
1212 cond_stdOK Nothing permissive (_, rep_tc, _)
1213 | null data_cons
1214 , not permissive = NotValid (no_cons_why rep_tc $$ suggestion)
1215 | not (null con_whys) = NotValid (vcat con_whys $$ suggestion)
1216 | otherwise = IsValid
1217 where
1218 suggestion = ptext (sLit "Possible fix: use a standalone deriving declaration instead")
1219 data_cons = tyConDataCons rep_tc
1220 con_whys = getInvalids (map check_con data_cons)
1221
1222 check_con :: DataCon -> Validity
1223 check_con con
1224 | not (isVanillaDataCon con)
1225 = NotValid (badCon con (ptext (sLit "has existentials or constraints in its type")))
1226 | not (permissive || all isTauTy (dataConOrigArgTys con))
1227 = NotValid (badCon con (ptext (sLit "has a higher-rank type")))
1228 | otherwise
1229 = IsValid
1230
1231 no_cons_why :: TyCon -> SDoc
1232 no_cons_why rep_tc = quotes (pprSourceTyCon rep_tc) <+>
1233 ptext (sLit "must have at least one data constructor")
1234
1235 cond_RepresentableOk :: Condition
1236 cond_RepresentableOk (_, tc, tc_args) = canDoGenerics tc tc_args
1237
1238 cond_Representable1Ok :: Condition
1239 cond_Representable1Ok (_, tc, tc_args) = canDoGenerics1 tc tc_args
1240
1241 cond_enumOrProduct :: Class -> Condition
1242 cond_enumOrProduct cls = cond_isEnumeration `orCond`
1243 (cond_isProduct `andCond` cond_args cls)
1244
1245 cond_args :: Class -> Condition
1246 -- For some classes (eg Eq, Ord) we allow unlifted arg types
1247 -- by generating specialised code. For others (eg Data) we don't.
1248 cond_args cls (_, tc, _)
1249 = case bad_args of
1250 [] -> IsValid
1251 (ty:_) -> NotValid (hang (ptext (sLit "Don't know how to derive") <+> quotes (ppr cls))
1252 2 (ptext (sLit "for type") <+> quotes (ppr ty)))
1253 where
1254 bad_args = [ arg_ty | con <- tyConDataCons tc
1255 , arg_ty <- dataConOrigArgTys con
1256 , isUnLiftedType arg_ty
1257 , not (ok_ty arg_ty) ]
1258
1259 cls_key = classKey cls
1260 ok_ty arg_ty
1261 | cls_key == eqClassKey = check_in arg_ty ordOpTbl
1262 | cls_key == ordClassKey = check_in arg_ty ordOpTbl
1263 | cls_key == showClassKey = check_in arg_ty boxConTbl
1264 | cls_key == liftClassKey = check_in arg_ty litConTbl
1265 | otherwise = False -- Read, Ix etc
1266
1267 check_in :: Type -> [(Type,a)] -> Bool
1268 check_in arg_ty tbl = any (eqType arg_ty . fst) tbl
1269
1270
1271 cond_isEnumeration :: Condition
1272 cond_isEnumeration (_, rep_tc, _)
1273 | isEnumerationTyCon rep_tc = IsValid
1274 | otherwise = NotValid why
1275 where
1276 why = sep [ quotes (pprSourceTyCon rep_tc) <+>
1277 ptext (sLit "must be an enumeration type")
1278 , ptext (sLit "(an enumeration consists of one or more nullary, non-GADT constructors)") ]
1279 -- See Note [Enumeration types] in TyCon
1280
1281 cond_isProduct :: Condition
1282 cond_isProduct (_, rep_tc, _)
1283 | isProductTyCon rep_tc = IsValid
1284 | otherwise = NotValid why
1285 where
1286 why = quotes (pprSourceTyCon rep_tc) <+>
1287 ptext (sLit "must have precisely one constructor")
1288
1289 functorLikeClassKeys :: [Unique]
1290 functorLikeClassKeys = [functorClassKey, foldableClassKey, traversableClassKey]
1291
1292 cond_functorOK :: Bool -> Bool -> Condition
1293 -- OK for Functor/Foldable/Traversable class
1294 -- Currently: (a) at least one argument
1295 -- (b) don't use argument contravariantly
1296 -- (c) don't use argument in the wrong place, e.g. data T a = T (X a a)
1297 -- (d) optionally: don't use function types
1298 -- (e) no "stupid context" on data type
1299 cond_functorOK allowFunctions allowExQuantifiedLastTyVar (_, rep_tc, _)
1300 | null tc_tvs
1301 = NotValid (ptext (sLit "Data type") <+> quotes (ppr rep_tc)
1302 <+> ptext (sLit "must have some type parameters"))
1303
1304 | not (null bad_stupid_theta)
1305 = NotValid (ptext (sLit "Data type") <+> quotes (ppr rep_tc)
1306 <+> ptext (sLit "must not have a class context:") <+> pprTheta bad_stupid_theta)
1307
1308 | otherwise
1309 = allValid (map check_con data_cons)
1310 where
1311 tc_tvs = tyConTyVars rep_tc
1312 Just (_, last_tv) = snocView tc_tvs
1313 bad_stupid_theta = filter is_bad (tyConStupidTheta rep_tc)
1314 is_bad pred = last_tv `elemVarSet` tyVarsOfType pred
1315
1316 data_cons = tyConDataCons rep_tc
1317 check_con con = allValid (check_universal con : foldDataConArgs (ft_check con) con)
1318
1319 check_universal :: DataCon -> Validity
1320 check_universal con
1321 | allowExQuantifiedLastTyVar
1322 = IsValid -- See Note [DeriveFoldable with ExistentialQuantification]
1323 -- in TcGenDeriv
1324 | Just tv <- getTyVar_maybe (last (tyConAppArgs (dataConOrigResTy con)))
1325 , tv `elem` dataConUnivTyVars con
1326 , not (tv `elemVarSet` tyVarsOfTypes (dataConTheta con))
1327 = IsValid -- See Note [Check that the type variable is truly universal]
1328 | otherwise
1329 = NotValid (badCon con existential)
1330
1331 ft_check :: DataCon -> FFoldType Validity
1332 ft_check con = FT { ft_triv = IsValid, ft_var = IsValid
1333 , ft_co_var = NotValid (badCon con covariant)
1334 , ft_fun = \x y -> if allowFunctions then x `andValid` y
1335 else NotValid (badCon con functions)
1336 , ft_tup = \_ xs -> allValid xs
1337 , ft_ty_app = \_ x -> x
1338 , ft_bad_app = NotValid (badCon con wrong_arg)
1339 , ft_forall = \_ x -> x }
1340
1341 existential = ptext (sLit "must be truly polymorphic in the last argument of the data type")
1342 covariant = ptext (sLit "must not use the type variable in a function argument")
1343 functions = ptext (sLit "must not contain function types")
1344 wrong_arg = ptext (sLit "must use the type variable only as the last argument of a data type")
1345
1346 checkFlag :: ExtensionFlag -> Condition
1347 checkFlag flag (dflags, _, _)
1348 | xopt flag dflags = IsValid
1349 | otherwise = NotValid why
1350 where
1351 why = ptext (sLit "You need ") <> text flag_str
1352 <+> ptext (sLit "to derive an instance for this class")
1353 flag_str = case [ flagSpecName f | f <- xFlags , flagSpecFlag f == flag ] of
1354 [s] -> s
1355 other -> pprPanic "checkFlag" (ppr other)
1356
1357 std_class_via_coercible :: Class -> Bool
1358 -- These standard classes can be derived for a newtype
1359 -- using the coercible trick *even if no -XGeneralizedNewtypeDeriving
1360 -- because giving so gives the same results as generating the boilerplate
1361 std_class_via_coercible clas
1362 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
1363 -- Not Read/Show/Lift because they respect the type
1364 -- Not Enum, because newtypes are never in Enum
1365
1366
1367 non_coercible_class :: Class -> Bool
1368 -- *Never* derive Read, Show, Typeable, Data, Generic, Generic1, Lift
1369 -- by Coercible, even with -XGeneralizedNewtypeDeriving
1370 -- Also, avoid Traversable, as the Coercible-derived instance and the "normal"-derived
1371 -- instance behave differently if there's a non-lawful Applicative out there.
1372 -- Besides, with roles, Coercible-deriving Traversable is ill-roled.
1373 non_coercible_class cls
1374 = classKey cls `elem` ([ readClassKey, showClassKey, dataClassKey
1375 , genClassKey, gen1ClassKey, typeableClassKey
1376 , traversableClassKey, liftClassKey ])
1377
1378 new_dfun_name :: Class -> TyCon -> TcM Name
1379 new_dfun_name clas tycon -- Just a simple wrapper
1380 = do { loc <- getSrcSpanM -- The location of the instance decl, not of the tycon
1381 ; newDFunName clas [mkTyConApp tycon []] loc }
1382 -- The type passed to newDFunName is only used to generate
1383 -- a suitable string; hence the empty type arg list
1384
1385 badCon :: DataCon -> SDoc -> SDoc
1386 badCon con msg = ptext (sLit "Constructor") <+> quotes (ppr con) <+> msg
1387
1388 {-
1389 Note [Check that the type variable is truly universal]
1390 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1391 For Functor and Traversable instances, we must check that the *last argument*
1392 of the type constructor is used truly universally quantified. Example
1393
1394 data T a b where
1395 T1 :: a -> b -> T a b -- Fine! Vanilla H-98
1396 T2 :: b -> c -> T a b -- Fine! Existential c, but we can still map over 'b'
1397 T3 :: b -> T Int b -- Fine! Constraint 'a', but 'b' is still polymorphic
1398 T4 :: Ord b => b -> T a b -- No! 'b' is constrained
1399 T5 :: b -> T b b -- No! 'b' is constrained
1400 T6 :: T a (b,b) -- No! 'b' is constrained
1401
1402 Notice that only the first of these constructors is vanilla H-98. We only
1403 need to take care about the last argument (b in this case). See Trac #8678.
1404 Eg. for T1-T3 we can write
1405
1406 fmap f (T1 a b) = T1 a (f b)
1407 fmap f (T2 b c) = T2 (f b) c
1408 fmap f (T3 x) = T3 (f x)
1409
1410 We need not perform these checks for Foldable instances, however, since
1411 functions in Foldable can only consume existentially quantified type variables,
1412 rather than produce them (as is the case in Functor and Traversable functions.)
1413 As a result, T can have a derived Foldable instance:
1414
1415 foldr f z (T1 a b) = f b z
1416 foldr f z (T2 b c) = f b z
1417 foldr f z (T3 x) = f x z
1418 foldr f z (T4 x) = f x z
1419 foldr f z (T5 x) = f x z
1420 foldr _ z T6 = z
1421
1422 See Note [DeriveFoldable with ExistentialQuantification] in TcGenDeriv.
1423
1424
1425 Note [Superclasses of derived instance]
1426 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1427 In general, a derived instance decl needs the superclasses of the derived
1428 class too. So if we have
1429 data T a = ...deriving( Ord )
1430 then the initial context for Ord (T a) should include Eq (T a). Often this is
1431 redundant; we'll also generate an Ord constraint for each constructor argument,
1432 and that will probably generate enough constraints to make the Eq (T a) constraint
1433 be satisfied too. But not always; consider:
1434
1435 data S a = S
1436 instance Eq (S a)
1437 instance Ord (S a)
1438
1439 data T a = MkT (S a) deriving( Ord )
1440 instance Num a => Eq (T a)
1441
1442 The derived instance for (Ord (T a)) must have a (Num a) constraint!
1443 Similarly consider:
1444 data T a = MkT deriving( Data, Typeable )
1445 Here there *is* no argument field, but we must nevertheless generate
1446 a context for the Data instances:
1447 instance Typable a => Data (T a) where ...
1448
1449
1450 ************************************************************************
1451 * *
1452 Deriving newtypes
1453 * *
1454 ************************************************************************
1455 -}
1456
1457 mkNewTypeEqn :: DynFlags -> Maybe OverlapMode -> [Var] -> Class
1458 -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
1459 -> DerivContext
1460 -> TcRn EarlyDerivSpec
1461 mkNewTypeEqn dflags overlap_mode tvs
1462 cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
1463 -- Want: instance (...) => cls (cls_tys ++ [tycon tc_args]) where ...
1464 | ASSERT( length cls_tys + 1 == classArity cls )
1465 might_derive_via_coercible && ((newtype_deriving && not deriveAnyClass)
1466 || std_class_via_coercible cls)
1467 = do traceTc "newtype deriving:" (ppr tycon <+> ppr rep_tys <+> ppr all_preds)
1468 dfun_name <- new_dfun_name cls tycon
1469 loc <- getSrcSpanM
1470 case mtheta of
1471 Just theta -> return $ GivenTheta $ DS
1472 { ds_loc = loc
1473 , ds_name = dfun_name, ds_tvs = varSetElemsKvsFirst dfun_tvs
1474 , ds_cls = cls, ds_tys = inst_tys
1475 , ds_tc = rep_tycon, ds_tc_args = rep_tc_args
1476 , ds_theta = theta
1477 , ds_overlap = overlap_mode
1478 , ds_newtype = True }
1479 Nothing -> return $ InferTheta $ DS
1480 { ds_loc = loc
1481 , ds_name = dfun_name, ds_tvs = varSetElemsKvsFirst dfun_tvs
1482 , ds_cls = cls, ds_tys = inst_tys
1483 , ds_tc = rep_tycon, ds_tc_args = rep_tc_args
1484 , ds_theta = all_preds
1485 , ds_overlap = overlap_mode
1486 , ds_newtype = True }
1487 | otherwise
1488 = case checkSideConditions dflags mtheta cls cls_tys rep_tycon rep_tc_args of
1489 -- Error with standard class
1490 DerivableClassError msg
1491 | might_derive_via_coercible -> bale_out (msg $$ suggest_gnd)
1492 | otherwise -> bale_out msg
1493
1494 -- Must use newtype deriving or DeriveAnyClass
1495 NonDerivableClass _msg
1496 -- Too hard, even with newtype deriving
1497 | newtype_deriving -> bale_out cant_derive_err
1498 -- Try newtype deriving!
1499 -- Here we suggest GeneralizedNewtypeDeriving even in cases where it may
1500 -- not be applicable. See Trac #9600.
1501 | otherwise -> bale_out (non_std $$ suggest_gnd)
1502
1503 -- CanDerive/DerivableViaInstance
1504 _ -> do when (newtype_deriving && deriveAnyClass) $
1505 addWarnTc (sep [ ptext (sLit "Both DeriveAnyClass and GeneralizedNewtypeDeriving are enabled")
1506 , ptext (sLit "Defaulting to the DeriveAnyClass strategy for instantiating") <+> ppr cls ])
1507 go_for_it
1508 where
1509 newtype_deriving = xopt Opt_GeneralizedNewtypeDeriving dflags
1510 deriveAnyClass = xopt Opt_DeriveAnyClass dflags
1511 go_for_it = mk_data_eqn overlap_mode tvs cls tycon tc_args
1512 rep_tycon rep_tc_args mtheta
1513 bale_out = bale_out' newtype_deriving
1514 bale_out' b = failWithTc . derivingThingErr b cls cls_tys inst_ty
1515
1516 non_std = nonStdErr cls
1517 suggest_gnd = ptext (sLit "Try GeneralizedNewtypeDeriving for GHC's newtype-deriving extension")
1518
1519 -- Here is the plan for newtype derivings. We see
1520 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
1521 -- where t is a type,
1522 -- ak+1...an is a suffix of a1..an, and are all tyars
1523 -- ak+1...an do not occur free in t, nor in the s1..sm
1524 -- (C s1 ... sm) is a *partial applications* of class C
1525 -- with the last parameter missing
1526 -- (T a1 .. ak) matches the kind of C's last argument
1527 -- (and hence so does t)
1528 -- The latter kind-check has been done by deriveTyData already,
1529 -- and tc_args are already trimmed
1530 --
1531 -- We generate the instance
1532 -- instance forall ({a1..ak} u fvs(s1..sm)).
1533 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
1534 -- where T a1...ap is the partial application of
1535 -- the LHS of the correct kind and p >= k
1536 --
1537 -- NB: the variables below are:
1538 -- tc_tvs = [a1, ..., an]
1539 -- tyvars_to_keep = [a1, ..., ak]
1540 -- rep_ty = t ak .. an
1541 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
1542 -- tys = [s1, ..., sm]
1543 -- rep_fn' = t
1544 --
1545 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
1546 -- We generate the instance
1547 -- instance Monad (ST s) => Monad (T s) where
1548
1549 nt_eta_arity = newTyConEtadArity rep_tycon
1550 -- For newtype T a b = MkT (S a a b), the TyCon machinery already
1551 -- eta-reduces the representation type, so we know that
1552 -- T a ~ S a a
1553 -- That's convenient here, because we may have to apply
1554 -- it to fewer than its original complement of arguments
1555
1556 -- Note [Newtype representation]
1557 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1558 -- Need newTyConRhs (*not* a recursive representation finder)
1559 -- to get the representation type. For example
1560 -- newtype B = MkB Int
1561 -- newtype A = MkA B deriving( Num )
1562 -- We want the Num instance of B, *not* the Num instance of Int,
1563 -- when making the Num instance of A!
1564 rep_inst_ty = newTyConInstRhs rep_tycon rep_tc_args
1565 rep_tys = cls_tys ++ [rep_inst_ty]
1566 rep_pred = mkClassPred cls rep_tys
1567 rep_pred_o = mkPredOrigin DerivOrigin rep_pred
1568 -- rep_pred is the representation dictionary, from where
1569 -- we are gong to get all the methods for the newtype
1570 -- dictionary
1571
1572
1573 -- Next we figure out what superclass dictionaries to use
1574 -- See Note [Newtype deriving superclasses] above
1575
1576 cls_tyvars = classTyVars cls
1577 dfun_tvs = tyVarsOfTypes inst_tys
1578 inst_ty = mkTyConApp tycon tc_args
1579 inst_tys = cls_tys ++ [inst_ty]
1580 sc_theta =
1581 mkThetaOrigin DerivOrigin $
1582 substTheta (zipOpenTvSubst cls_tyvars inst_tys) (classSCTheta cls)
1583
1584
1585 -- Next we collect Coercible constraints between
1586 -- the Class method types, instantiated with the representation and the
1587 -- newtype type; precisely the constraints required for the
1588 -- calls to coercible that we are going to generate.
1589 coercible_constraints =
1590 [ let (Pair t1 t2) = mkCoerceClassMethEqn cls (varSetElemsKvsFirst dfun_tvs) inst_tys rep_inst_ty meth
1591 in mkPredOrigin (DerivOriginCoerce meth t1 t2) (mkCoerciblePred t1 t2)
1592 | meth <- classMethods cls ]
1593
1594 -- If there are no tyvars, there's no need
1595 -- to abstract over the dictionaries we need
1596 -- Example: newtype T = MkT Int deriving( C )
1597 -- We get the derived instance
1598 -- instance C T
1599 -- rather than
1600 -- instance C Int => C T
1601 all_preds = rep_pred_o : coercible_constraints ++ sc_theta -- NB: rep_pred comes first
1602
1603 -------------------------------------------------------------------
1604 -- Figuring out whether we can only do this newtype-deriving thing
1605
1606 -- See Note [Determining whether newtype-deriving is appropriate]
1607 might_derive_via_coercible
1608 = not (non_coercible_class cls)
1609 && eta_ok
1610 && ats_ok
1611 -- && not (isRecursiveTyCon tycon) -- Note [Recursive newtypes]
1612
1613 -- Check that eta reduction is OK
1614 eta_ok = nt_eta_arity <= length rep_tc_args
1615 -- The newtype can be eta-reduced to match the number
1616 -- of type argument actually supplied
1617 -- newtype T a b = MkT (S [a] b) deriving( Monad )
1618 -- Here the 'b' must be the same in the rep type (S [a] b)
1619 -- And the [a] must not mention 'b'. That's all handled
1620 -- by nt_eta_rity.
1621
1622 ats_ok = null (classATs cls)
1623 -- No associated types for the class, because we don't
1624 -- currently generate type 'instance' decls; and cannot do
1625 -- so for 'data' instance decls
1626
1627 cant_derive_err
1628 = vcat [ ppUnless eta_ok eta_msg
1629 , ppUnless ats_ok ats_msg ]
1630 eta_msg = ptext (sLit "cannot eta-reduce the representation type enough")
1631 ats_msg = ptext (sLit "the class has associated types")
1632
1633 {-
1634 Note [Recursive newtypes]
1635 ~~~~~~~~~~~~~~~~~~~~~~~~~
1636 Newtype deriving works fine, even if the newtype is recursive.
1637 e.g. newtype S1 = S1 [T1 ()]
1638 newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
1639 Remember, too, that type families are currently (conservatively) given
1640 a recursive flag, so this also allows newtype deriving to work
1641 for type famillies.
1642
1643 We used to exclude recursive types, because we had a rather simple
1644 minded way of generating the instance decl:
1645 newtype A = MkA [A]
1646 instance Eq [A] => Eq A -- Makes typechecker loop!
1647 But now we require a simple context, so it's ok.
1648
1649 Note [Determining whether newtype-deriving is appropriate]
1650 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1651 When we see
1652 newtype NT = MkNT Foo
1653 deriving C
1654 we have to decide how to perform the deriving. Do we do newtype deriving,
1655 or do we do normal deriving? In general, we prefer to do newtype deriving
1656 wherever possible. So, we try newtype deriving unless there's a glaring
1657 reason not to.
1658
1659 Note that newtype deriving might fail, even after we commit to it. This
1660 is because the derived instance uses `coerce`, which must satisfy its
1661 `Coercible` constraint. This is different than other deriving scenarios,
1662 where we're sure that the resulting instance will type-check.
1663
1664 ************************************************************************
1665 * *
1666 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
1667 * *
1668 ************************************************************************
1669
1670 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
1671 terms, which is the final correct RHS for the corresponding original
1672 equation.
1673 \begin{itemize}
1674 \item
1675 Each (k,TyVarTy tv) in a solution constrains only a type
1676 variable, tv.
1677
1678 \item
1679 The (k,TyVarTy tv) pairs in a solution are canonically
1680 ordered by sorting on type varible, tv, (major key) and then class, k,
1681 (minor key)
1682 \end{itemize}
1683 -}
1684
1685 inferInstanceContexts :: [DerivSpec ThetaOrigin] -> TcM [DerivSpec ThetaType]
1686
1687 inferInstanceContexts [] = return []
1688
1689 inferInstanceContexts infer_specs
1690 = do { traceTc "inferInstanceContexts" $ vcat (map pprDerivSpec infer_specs)
1691 ; iterate_deriv 1 initial_solutions }
1692 where
1693 ------------------------------------------------------------------
1694 -- The initial solutions for the equations claim that each
1695 -- instance has an empty context; this solution is certainly
1696 -- in canonical form.
1697 initial_solutions :: [ThetaType]
1698 initial_solutions = [ [] | _ <- infer_specs ]
1699
1700 ------------------------------------------------------------------
1701 -- iterate_deriv calculates the next batch of solutions,
1702 -- compares it with the current one; finishes if they are the
1703 -- same, otherwise recurses with the new solutions.
1704 -- It fails if any iteration fails
1705 iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec ThetaType]
1706 iterate_deriv n current_solns
1707 | n > 20 -- Looks as if we are in an infinite loop
1708 -- This can happen if we have -XUndecidableInstances
1709 -- (See TcSimplify.tcSimplifyDeriv.)
1710 = pprPanic "solveDerivEqns: probable loop"
1711 (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
1712 | otherwise
1713 = do { -- Extend the inst info from the explicit instance decls
1714 -- with the current set of solutions, and simplify each RHS
1715 inst_specs <- zipWithM newDerivClsInst current_solns infer_specs
1716 ; new_solns <- checkNoErrs $
1717 extendLocalInstEnv inst_specs $
1718 mapM gen_soln infer_specs
1719
1720 ; if (current_solns `eqSolution` new_solns) then
1721 return [ spec { ds_theta = soln }
1722 | (spec, soln) <- zip infer_specs current_solns ]
1723 else
1724 iterate_deriv (n+1) new_solns }
1725
1726 eqSolution = eqListBy (eqListBy eqType)
1727
1728 ------------------------------------------------------------------
1729 gen_soln :: DerivSpec ThetaOrigin -> TcM ThetaType
1730 gen_soln (DS { ds_loc = loc, ds_tvs = tyvars
1731 , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
1732 = setSrcSpan loc $
1733 addErrCtxt (derivInstCtxt the_pred) $
1734 do { theta <- simplifyDeriv the_pred tyvars deriv_rhs
1735 -- checkValidInstance tyvars theta clas inst_tys
1736 -- Not necessary; see Note [Exotic derived instance contexts]
1737
1738 ; traceTc "TcDeriv" (ppr deriv_rhs $$ ppr theta)
1739 -- Claim: the result instance declaration is guaranteed valid
1740 -- Hence no need to call:
1741 -- checkValidInstance tyvars theta clas inst_tys
1742 ; return (sortBy cmpType theta) } -- Canonicalise before returning the solution
1743 where
1744 the_pred = mkClassPred clas inst_tys
1745
1746 ------------------------------------------------------------------
1747 newDerivClsInst :: ThetaType -> DerivSpec theta -> TcM ClsInst
1748 newDerivClsInst theta (DS { ds_name = dfun_name, ds_overlap = overlap_mode
1749 , ds_tvs = tvs, ds_cls = clas, ds_tys = tys })
1750 = newClsInst overlap_mode dfun_name tvs theta clas tys
1751
1752 extendLocalInstEnv :: [ClsInst] -> TcM a -> TcM a
1753 -- Add new locally-defined instances; don't bother to check
1754 -- for functional dependency errors -- that'll happen in TcInstDcls
1755 extendLocalInstEnv dfuns thing_inside
1756 = do { env <- getGblEnv
1757 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
1758 env' = env { tcg_inst_env = inst_env' }
1759 ; setGblEnv env' thing_inside }
1760
1761 {-
1762 ***********************************************************************************
1763 * *
1764 * Simplify derived constraints
1765 * *
1766 ***********************************************************************************
1767 -}
1768
1769 simplifyDeriv :: PredType
1770 -> [TyVar]
1771 -> ThetaOrigin -- Wanted
1772 -> TcM ThetaType -- Needed
1773 -- Given instance (wanted) => C inst_ty
1774 -- Simplify 'wanted' as much as possibles
1775 -- Fail if not possible
1776 simplifyDeriv pred tvs theta
1777 = do { (skol_subst, tvs_skols) <- tcInstSkolTyVars tvs -- Skolemize
1778 -- The constraint solving machinery
1779 -- expects *TcTyVars* not TyVars.
1780 -- We use *non-overlappable* (vanilla) skolems
1781 -- See Note [Overlap and deriving]
1782
1783 ; let skol_set = mkVarSet tvs_skols
1784 doc = ptext (sLit "deriving") <+> parens (ppr pred)
1785
1786 ; wanted <- mapM (\(PredOrigin t o) -> newWanted o (substTy skol_subst t)) theta
1787
1788 ; traceTc "simplifyDeriv" $
1789 vcat [ pprTvBndrs tvs $$ ppr theta $$ ppr wanted, doc ]
1790 ; residual_wanted <- solveWantedsTcM wanted
1791
1792 ; residual_simple <- zonkSimples (wc_simple residual_wanted)
1793 ; let (good, bad) = partitionBagWith get_good residual_simple
1794 -- See Note [Exotic derived instance contexts]
1795 get_good :: Ct -> Either PredType Ct
1796 get_good ct | validDerivPred skol_set p
1797 , isWantedCt ct = Left p
1798 -- NB: residual_wanted may contain unsolved
1799 -- Derived and we stick them into the bad set
1800 -- so that reportUnsolved may decide what to do with them
1801 | otherwise = Right ct
1802 where p = ctPred ct
1803
1804 ; traceTc "simplifyDeriv 2" $
1805 vcat [ ppr tvs_skols, ppr residual_simple, ppr good, ppr bad ]
1806
1807 -- If we are deferring type errors, simply ignore any insoluble
1808 -- constraints. They'll come up again when we typecheck the
1809 -- generated instance declaration
1810 ; defer <- goptM Opt_DeferTypeErrors
1811 ; unless defer (reportAllUnsolved (residual_wanted { wc_simple = bad }))
1812
1813 ; let min_theta = mkMinimalBySCs (bagToList good)
1814 subst_skol = zipTopTvSubst tvs_skols $ map mkTyVarTy tvs
1815 -- The reverse substitution (sigh)
1816 ; return (substTheta subst_skol min_theta) }
1817
1818 {-
1819 Note [Overlap and deriving]
1820 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1821 Consider some overlapping instances:
1822 data Show a => Show [a] where ..
1823 data Show [Char] where ...
1824
1825 Now a data type with deriving:
1826 data T a = MkT [a] deriving( Show )
1827
1828 We want to get the derived instance
1829 instance Show [a] => Show (T a) where...
1830 and NOT
1831 instance Show a => Show (T a) where...
1832 so that the (Show (T Char)) instance does the Right Thing
1833
1834 It's very like the situation when we're inferring the type
1835 of a function
1836 f x = show [x]
1837 and we want to infer
1838 f :: Show [a] => a -> String
1839
1840 BOTTOM LINE: use vanilla, non-overlappable skolems when inferring
1841 the context for the derived instance.
1842 Hence tcInstSkolTyVars not tcInstSuperSkolTyVars
1843
1844 Note [Exotic derived instance contexts]
1845 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1846 In a 'derived' instance declaration, we *infer* the context. It's a
1847 bit unclear what rules we should apply for this; the Haskell report is
1848 silent. Obviously, constraints like (Eq a) are fine, but what about
1849 data T f a = MkT (f a) deriving( Eq )
1850 where we'd get an Eq (f a) constraint. That's probably fine too.
1851
1852 One could go further: consider
1853 data T a b c = MkT (Foo a b c) deriving( Eq )
1854 instance (C Int a, Eq b, Eq c) => Eq (Foo a b c)
1855
1856 Notice that this instance (just) satisfies the Paterson termination
1857 conditions. Then we *could* derive an instance decl like this:
1858
1859 instance (C Int a, Eq b, Eq c) => Eq (T a b c)
1860 even though there is no instance for (C Int a), because there just
1861 *might* be an instance for, say, (C Int Bool) at a site where we
1862 need the equality instance for T's.
1863
1864 However, this seems pretty exotic, and it's quite tricky to allow
1865 this, and yet give sensible error messages in the (much more common)
1866 case where we really want that instance decl for C.
1867
1868 So for now we simply require that the derived instance context
1869 should have only type-variable constraints.
1870
1871 Here is another example:
1872 data Fix f = In (f (Fix f)) deriving( Eq )
1873 Here, if we are prepared to allow -XUndecidableInstances we
1874 could derive the instance
1875 instance Eq (f (Fix f)) => Eq (Fix f)
1876 but this is so delicate that I don't think it should happen inside
1877 'deriving'. If you want this, write it yourself!
1878
1879 NB: if you want to lift this condition, make sure you still meet the
1880 termination conditions! If not, the deriving mechanism generates
1881 larger and larger constraints. Example:
1882 data Succ a = S a
1883 data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
1884
1885 Note the lack of a Show instance for Succ. First we'll generate
1886 instance (Show (Succ a), Show a) => Show (Seq a)
1887 and then
1888 instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
1889 and so on. Instead we want to complain of no instance for (Show (Succ a)).
1890
1891 The bottom line
1892 ~~~~~~~~~~~~~~~
1893 Allow constraints which consist only of type variables, with no repeats.
1894
1895
1896 ************************************************************************
1897 * *
1898 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
1899 * *
1900 ************************************************************************
1901
1902 After all the trouble to figure out the required context for the
1903 derived instance declarations, all that's left is to chug along to
1904 produce them. They will then be shoved into @tcInstDecls2@, which
1905 will do all its usual business.
1906
1907 There are lots of possibilities for code to generate. Here are
1908 various general remarks.
1909
1910 PRINCIPLES:
1911 \begin{itemize}
1912 \item
1913 We want derived instances of @Eq@ and @Ord@ (both v common) to be
1914 ``you-couldn't-do-better-by-hand'' efficient.
1915
1916 \item
1917 Deriving @Show@---also pretty common--- should also be reasonable good code.
1918
1919 \item
1920 Deriving for the other classes isn't that common or that big a deal.
1921 \end{itemize}
1922
1923 PRAGMATICS:
1924
1925 \begin{itemize}
1926 \item
1927 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
1928
1929 \item
1930 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
1931
1932 \item
1933 We {\em normally} generate code only for the non-defaulted methods;
1934 there are some exceptions for @Eq@ and (especially) @Ord@...
1935
1936 \item
1937 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
1938 constructor's numeric (@Int#@) tag. These are generated by
1939 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
1940 these is around is given by @hasCon2TagFun@.
1941
1942 The examples under the different sections below will make this
1943 clearer.
1944
1945 \item
1946 Much less often (really just for deriving @Ix@), we use a
1947 @_tag2con_<tycon>@ function. See the examples.
1948
1949 \item
1950 We use the renamer!!! Reason: we're supposed to be
1951 producing @LHsBinds Name@ for the methods, but that means
1952 producing correctly-uniquified code on the fly. This is entirely
1953 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
1954 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
1955 the renamer. What a great hack!
1956 \end{itemize}
1957 -}
1958
1959 -- Generate the InstInfo for the required instance paired with the
1960 -- *representation* tycon for that instance,
1961 -- plus any auxiliary bindings required
1962 --
1963 -- Representation tycons differ from the tycon in the instance signature in
1964 -- case of instances for indexed families.
1965 --
1966 genInst :: CommonAuxiliaries
1967 -> DerivSpec ThetaType
1968 -> TcM (InstInfo RdrName, BagDerivStuff, Maybe Name)
1969 genInst comauxs
1970 spec@(DS { ds_tvs = tvs, ds_tc = rep_tycon, ds_tc_args = rep_tc_args
1971 , ds_theta = theta, ds_newtype = is_newtype, ds_tys = tys
1972 , ds_name = dfun_name, ds_cls = clas, ds_loc = loc })
1973 | is_newtype -- See Note [Bindings for Generalised Newtype Deriving]
1974 = do { inst_spec <- newDerivClsInst theta spec
1975 ; traceTc "genInst/is_newtype" (vcat [ppr loc, ppr clas, ppr tvs, ppr tys, ppr rhs_ty])
1976 ; return ( InstInfo
1977 { iSpec = inst_spec
1978 , iBinds = InstBindings
1979 { ib_binds = gen_Newtype_binds loc clas tvs tys rhs_ty
1980 , ib_tyvars = map Var.varName tvs -- Scope over bindings
1981 , ib_pragmas = []
1982 , ib_extensions = [ Opt_ImpredicativeTypes
1983 , Opt_RankNTypes ]
1984 , ib_derived = True } }
1985 , emptyBag
1986 , Just $ getName $ head $ tyConDataCons rep_tycon ) }
1987 -- See Note [Newtype deriving and unused constructors]
1988
1989 | otherwise
1990 = do { (meth_binds, deriv_stuff) <- genDerivStuff loc clas
1991 dfun_name rep_tycon
1992 (lookupNameEnv comauxs
1993 (tyConName rep_tycon))
1994 ; inst_spec <- newDerivClsInst theta spec
1995 ; traceTc "newder" (ppr inst_spec)
1996 ; let inst_info = InstInfo { iSpec = inst_spec
1997 , iBinds = InstBindings
1998 { ib_binds = meth_binds
1999 , ib_tyvars = map Var.varName tvs
2000 , ib_pragmas = []
2001 , ib_extensions = []
2002 , ib_derived = True } }
2003 ; return ( inst_info, deriv_stuff, Nothing ) }
2004 where
2005 rhs_ty = newTyConInstRhs rep_tycon rep_tc_args
2006
2007 genDerivStuff :: SrcSpan -> Class -> Name -> TyCon
2008 -> Maybe CommonAuxiliary
2009 -> TcM (LHsBinds RdrName, BagDerivStuff)
2010 genDerivStuff loc clas dfun_name tycon comaux_maybe
2011 | let ck = classKey clas
2012 , ck `elem` [genClassKey, gen1ClassKey] -- Special case because monadic
2013 = let gk = if ck == genClassKey then Gen0 else Gen1
2014 -- TODO NSF: correctly identify when we're building Both instead of One
2015 Just metaTyCons = comaux_maybe -- well-guarded by commonAuxiliaries and genInst
2016 in do
2017 (binds, faminst) <- gen_Generic_binds gk tycon metaTyCons (nameModule dfun_name)
2018 return (binds, unitBag (DerivFamInst faminst))
2019
2020 | otherwise -- Non-monadic generators
2021 = do { dflags <- getDynFlags
2022 ; fix_env <- getDataConFixityFun tycon
2023 ; return (genDerivedBinds dflags fix_env clas loc tycon) }
2024
2025 getDataConFixityFun :: TyCon -> TcM (Name -> Fixity)
2026 -- If the TyCon is locally defined, we want the local fixity env;
2027 -- but if it is imported (which happens for standalone deriving)
2028 -- we need to get the fixity env from the interface file
2029 -- c.f. RnEnv.lookupFixity, and Trac #9830
2030 getDataConFixityFun tc
2031 = do { this_mod <- getModule
2032 ; if nameIsLocalOrFrom this_mod name
2033 then do { fix_env <- getFixityEnv
2034 ; return (lookupFixity fix_env) }
2035 else do { iface <- loadInterfaceForName doc name
2036 -- Should already be loaded!
2037 ; return (mi_fix_fn iface . nameOccName) } }
2038 where
2039 name = tyConName tc
2040 doc = ptext (sLit "Data con fixities for") <+> ppr name
2041
2042 {-
2043 Note [Bindings for Generalised Newtype Deriving]
2044 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2045 Consider
2046 class Eq a => C a where
2047 f :: a -> a
2048 newtype N a = MkN [a] deriving( C )
2049 instance Eq (N a) where ...
2050
2051 The 'deriving C' clause generates, in effect
2052 instance (C [a], Eq a) => C (N a) where
2053 f = coerce (f :: [a] -> [a])
2054
2055 This generates a cast for each method, but allows the superclasse to
2056 be worked out in the usual way. In this case the superclass (Eq (N
2057 a)) will be solved by the explicit Eq (N a) instance. We do *not*
2058 create the superclasses by casting the superclass dictionaries for the
2059 representation type.
2060
2061 See the paper "Safe zero-cost coercions for Hsakell".
2062
2063
2064 ************************************************************************
2065 * *
2066 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
2067 * *
2068 ************************************************************************
2069 -}
2070
2071 derivingNullaryErr :: MsgDoc
2072 derivingNullaryErr = ptext (sLit "Cannot derive instances for nullary classes")
2073
2074 derivingKindErr :: TyCon -> Class -> [Type] -> Kind -> MsgDoc
2075 derivingKindErr tc cls cls_tys cls_kind
2076 = hang (ptext (sLit "Cannot derive well-kinded instance of form")
2077 <+> quotes (pprClassPred cls cls_tys <+> parens (ppr tc <+> ptext (sLit "..."))))
2078 2 (ptext (sLit "Class") <+> quotes (ppr cls)
2079 <+> ptext (sLit "expects an argument of kind") <+> quotes (pprKind cls_kind))
2080
2081 derivingEtaErr :: Class -> [Type] -> Type -> MsgDoc
2082 derivingEtaErr cls cls_tys inst_ty
2083 = sep [ptext (sLit "Cannot eta-reduce to an instance of form"),
2084 nest 2 (ptext (sLit "instance (...) =>")
2085 <+> pprClassPred cls (cls_tys ++ [inst_ty]))]
2086
2087 derivingThingErr :: Bool -> Class -> [Type] -> Type -> MsgDoc -> MsgDoc
2088 derivingThingErr newtype_deriving clas tys ty why
2089 = sep [(hang (ptext (sLit "Can't make a derived instance of"))
2090 2 (quotes (ppr pred))
2091 $$ nest 2 extra) <> colon,
2092 nest 2 why]
2093 where
2094 extra | newtype_deriving = ptext (sLit "(even with cunning GeneralizedNewtypeDeriving)")
2095 | otherwise = Outputable.empty
2096 pred = mkClassPred clas (tys ++ [ty])
2097
2098 derivingHiddenErr :: TyCon -> SDoc
2099 derivingHiddenErr tc
2100 = hang (ptext (sLit "The data constructors of") <+> quotes (ppr tc) <+> ptext (sLit "are not all in scope"))
2101 2 (ptext (sLit "so you cannot derive an instance for it"))
2102
2103 standaloneCtxt :: LHsType Name -> SDoc
2104 standaloneCtxt ty = hang (ptext (sLit "In the stand-alone deriving instance for"))
2105 2 (quotes (ppr ty))
2106
2107 derivInstCtxt :: PredType -> MsgDoc
2108 derivInstCtxt pred
2109 = ptext (sLit "When deriving the instance for") <+> parens (ppr pred)