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