Show '#' on unboxed literals
[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 )
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 to box the Int# into an Int
1175 (which we know how to show), and append a '#'. Parenthesis are not required
1176 for unboxed values (`MkT -3#` is a valid expression).
1177
1178 Note [Deriving any class]
1179 ~~~~~~~~~~~~~~~~~~~~~~~~~
1180 Classic uses of a deriving clause, or a standalone-deriving declaration, are
1181 for:
1182 * a built-in class like Eq or Show, for which GHC knows how to generate
1183 the instance code
1184 * a newtype, via the mechanism enabled by GeneralizedNewtypeDeriving
1185
1186 The DeriveAnyClass extension adds a third way to derive instances, based on
1187 empty instance declarations.
1188
1189 The canonical use case is in combination with GHC.Generics and default method
1190 signatures. These allow us have have instance declarations be empty, but still
1191 useful, e.g.
1192
1193 data T a = ...blah..blah... deriving( Generic )
1194 instance C a => C (T a) -- No 'where' clause
1195
1196 where C is some "random" user-defined class.
1197
1198 This boilerplate code can be replaced by the more compact
1199
1200 data T a = ...blah..blah... deriving( Generic, C )
1201
1202 if DeriveAnyClass is enabled.
1203
1204 This is not restricted to Generics; any class can be derived, simply giving
1205 rise to an empty instance.
1206
1207 Unfortunately, it is not clear how to determine the context (in case of
1208 standard deriving; in standalone deriving, the user provides the context).
1209 GHC uses the same heuristic for figuring out the class context that it uses for
1210 Eq in the case of *-kinded classes, and for Functor in the case of
1211 * -> *-kinded classes. That may not be optimal or even wrong. But in such
1212 cases, standalone deriving can still be used.
1213 -}
1214
1215 ------------------------------------------------------------------
1216 -- Check side conditions that dis-allow derivability for particular classes
1217 -- This is *apart* from the newtype-deriving mechanism
1218 --
1219 -- Here we get the representation tycon in case of family instances as it has
1220 -- the data constructors - but we need to be careful to fall back to the
1221 -- family tycon (with indexes) in error messages.
1222
1223 data DerivStatus = CanDerive
1224 | DerivableClassError SDoc -- Standard class, but can't do it
1225 | DerivableViaInstance -- See Note [Deriving any class]
1226 | NonDerivableClass SDoc -- Non-standard class
1227
1228 checkSideConditions :: DynFlags -> DerivContext -> Class -> [TcType]
1229 -> TyCon -> [Type] -- tycon and its parameters
1230 -> DerivStatus
1231 checkSideConditions dflags mtheta cls cls_tys rep_tc rep_tc_args
1232 | Just cond <- sideConditions mtheta cls
1233 = case (cond (dflags, rep_tc, rep_tc_args)) of
1234 NotValid err -> DerivableClassError err -- Class-specific error
1235 IsValid | null cls_tys -> CanDerive -- All derivable classes are unary, so
1236 -- cls_tys (the type args other than last)
1237 -- should be null
1238 | otherwise -> DerivableClassError (classArgsErr cls cls_tys) -- e.g. deriving( Eq s )
1239 | otherwise = maybe DerivableViaInstance NonDerivableClass
1240 (canDeriveAnyClass dflags rep_tc cls)
1241
1242 classArgsErr :: Class -> [Type] -> SDoc
1243 classArgsErr cls cls_tys = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "is not a class")
1244
1245 nonStdErr :: Class -> SDoc
1246 nonStdErr cls = quotes (ppr cls) <+> ptext (sLit "is not a derivable class")
1247
1248 sideConditions :: DerivContext -> Class -> Maybe Condition
1249 sideConditions mtheta cls
1250 | cls_key == eqClassKey = Just (cond_std `andCond` cond_args cls)
1251 | cls_key == ordClassKey = Just (cond_std `andCond` cond_args cls)
1252 | cls_key == showClassKey = Just (cond_std `andCond` cond_args cls)
1253 | cls_key == readClassKey = Just (cond_std `andCond` cond_args cls)
1254 | cls_key == enumClassKey = Just (cond_std `andCond` cond_isEnumeration)
1255 | cls_key == ixClassKey = Just (cond_std `andCond` cond_enumOrProduct cls)
1256 | cls_key == boundedClassKey = Just (cond_std `andCond` cond_enumOrProduct cls)
1257 | cls_key == dataClassKey = Just (checkFlag Opt_DeriveDataTypeable `andCond`
1258 cond_std `andCond`
1259 cond_args cls)
1260 | cls_key == functorClassKey = Just (checkFlag Opt_DeriveFunctor `andCond`
1261 cond_vanilla `andCond`
1262 cond_functorOK True)
1263 | cls_key == foldableClassKey = Just (checkFlag Opt_DeriveFoldable `andCond`
1264 cond_vanilla `andCond`
1265 cond_functorOK False) -- Functor/Fold/Trav works ok for rank-n types
1266 | cls_key == traversableClassKey = Just (checkFlag Opt_DeriveTraversable `andCond`
1267 cond_vanilla `andCond`
1268 cond_functorOK False)
1269 | cls_key == genClassKey = Just (checkFlag Opt_DeriveGeneric `andCond`
1270 cond_vanilla `andCond`
1271 cond_RepresentableOk)
1272 | cls_key == gen1ClassKey = Just (checkFlag Opt_DeriveGeneric `andCond`
1273 cond_vanilla `andCond`
1274 cond_Representable1Ok)
1275 | otherwise = Nothing
1276 where
1277 cls_key = getUnique cls
1278 cond_std = cond_stdOK mtheta False -- Vanilla data constructors, at least one,
1279 -- and monotype arguments
1280 cond_vanilla = cond_stdOK mtheta True -- Vanilla data constructors but
1281 -- allow no data cons or polytype arguments
1282
1283 type Condition = (DynFlags, TyCon, [Type]) -> Validity
1284 -- first Bool is whether or not we are allowed to derive Data and Typeable
1285 -- second Bool is whether or not we are allowed to derive Functor
1286 -- TyCon is the *representation* tycon if the data type is an indexed one
1287 -- [Type] are the type arguments to the (representation) TyCon
1288 -- Nothing => OK
1289
1290 orCond :: Condition -> Condition -> Condition
1291 orCond c1 c2 tc
1292 = case (c1 tc, c2 tc) of
1293 (IsValid, _) -> IsValid -- c1 succeeds
1294 (_, IsValid) -> IsValid -- c21 succeeds
1295 (NotValid x, NotValid y) -> NotValid (x $$ ptext (sLit " or") $$ y)
1296 -- Both fail
1297
1298 andCond :: Condition -> Condition -> Condition
1299 andCond c1 c2 tc = c1 tc `andValid` c2 tc
1300
1301 cond_stdOK :: DerivContext -- Says whether this is standalone deriving or not;
1302 -- if standalone, we just say "yes, go for it"
1303 -> Bool -- True <=> permissive: allow higher rank
1304 -- args and no data constructors
1305 -> Condition
1306 cond_stdOK (Just _) _ _
1307 = IsValid -- Don't check these conservative conditions for
1308 -- standalone deriving; just generate the code
1309 -- and let the typechecker handle the result
1310 cond_stdOK Nothing permissive (_, rep_tc, _)
1311 | null data_cons
1312 , not permissive = NotValid (no_cons_why rep_tc $$ suggestion)
1313 | not (null con_whys) = NotValid (vcat con_whys $$ suggestion)
1314 | otherwise = IsValid
1315 where
1316 suggestion = ptext (sLit "Possible fix: use a standalone deriving declaration instead")
1317 data_cons = tyConDataCons rep_tc
1318 con_whys = getInvalids (map check_con data_cons)
1319
1320 check_con :: DataCon -> Validity
1321 check_con con
1322 | not (isVanillaDataCon con)
1323 = NotValid (badCon con (ptext (sLit "has existentials or constraints in its type")))
1324 | not (permissive || all isTauTy (dataConOrigArgTys con))
1325 = NotValid (badCon con (ptext (sLit "has a higher-rank type")))
1326 | otherwise
1327 = IsValid
1328
1329 no_cons_why :: TyCon -> SDoc
1330 no_cons_why rep_tc = quotes (pprSourceTyCon rep_tc) <+>
1331 ptext (sLit "must have at least one data constructor")
1332
1333 cond_RepresentableOk :: Condition
1334 cond_RepresentableOk (_, tc, tc_args) = canDoGenerics tc tc_args
1335
1336 cond_Representable1Ok :: Condition
1337 cond_Representable1Ok (_, tc, tc_args) = canDoGenerics1 tc tc_args
1338
1339 cond_enumOrProduct :: Class -> Condition
1340 cond_enumOrProduct cls = cond_isEnumeration `orCond`
1341 (cond_isProduct `andCond` cond_args cls)
1342
1343 cond_args :: Class -> Condition
1344 -- For some classes (eg Eq, Ord) we allow unlifted arg types
1345 -- by generating specialised code. For others (eg Data) we don't.
1346 cond_args cls (_, tc, _)
1347 = case bad_args of
1348 [] -> IsValid
1349 (ty:_) -> NotValid (hang (ptext (sLit "Don't know how to derive") <+> quotes (ppr cls))
1350 2 (ptext (sLit "for type") <+> quotes (ppr ty)))
1351 where
1352 bad_args = [ arg_ty | con <- tyConDataCons tc
1353 , arg_ty <- dataConOrigArgTys con
1354 , isUnLiftedType arg_ty
1355 , not (ok_ty arg_ty) ]
1356
1357 cls_key = classKey cls
1358 ok_ty arg_ty
1359 | cls_key == eqClassKey = check_in arg_ty ordOpTbl
1360 | cls_key == ordClassKey = check_in arg_ty ordOpTbl
1361 | cls_key == showClassKey = check_in arg_ty boxConTbl
1362 | otherwise = False -- Read, Ix etc
1363
1364 check_in :: Type -> [(Type,a)] -> Bool
1365 check_in arg_ty tbl = any (eqType arg_ty . fst) tbl
1366
1367
1368 cond_isEnumeration :: Condition
1369 cond_isEnumeration (_, rep_tc, _)
1370 | isEnumerationTyCon rep_tc = IsValid
1371 | otherwise = NotValid why
1372 where
1373 why = sep [ quotes (pprSourceTyCon rep_tc) <+>
1374 ptext (sLit "must be an enumeration type")
1375 , ptext (sLit "(an enumeration consists of one or more nullary, non-GADT constructors)") ]
1376 -- See Note [Enumeration types] in TyCon
1377
1378 cond_isProduct :: Condition
1379 cond_isProduct (_, rep_tc, _)
1380 | isProductTyCon rep_tc = IsValid
1381 | otherwise = NotValid why
1382 where
1383 why = quotes (pprSourceTyCon rep_tc) <+>
1384 ptext (sLit "must have precisely one constructor")
1385
1386 functorLikeClassKeys :: [Unique]
1387 functorLikeClassKeys = [functorClassKey, foldableClassKey, traversableClassKey]
1388
1389 cond_functorOK :: Bool -> Condition
1390 -- OK for Functor/Foldable/Traversable class
1391 -- Currently: (a) at least one argument
1392 -- (b) don't use argument contravariantly
1393 -- (c) don't use argument in the wrong place, e.g. data T a = T (X a a)
1394 -- (d) optionally: don't use function types
1395 -- (e) no "stupid context" on data type
1396 cond_functorOK allowFunctions (_, rep_tc, _)
1397 | null tc_tvs
1398 = NotValid (ptext (sLit "Data type") <+> quotes (ppr rep_tc)
1399 <+> ptext (sLit "must have some type parameters"))
1400
1401 | not (null bad_stupid_theta)
1402 = NotValid (ptext (sLit "Data type") <+> quotes (ppr rep_tc)
1403 <+> ptext (sLit "must not have a class context:") <+> pprTheta bad_stupid_theta)
1404
1405 | otherwise
1406 = allValid (map check_con data_cons)
1407 where
1408 tc_tvs = tyConTyVars rep_tc
1409 Just (_, last_tv) = snocView tc_tvs
1410 bad_stupid_theta = filter is_bad (tyConStupidTheta rep_tc)
1411 is_bad pred = last_tv `elemVarSet` tyVarsOfType pred
1412
1413 data_cons = tyConDataCons rep_tc
1414 check_con con = allValid (check_universal con : foldDataConArgs (ft_check con) con)
1415
1416 check_universal :: DataCon -> Validity
1417 check_universal con
1418 | Just tv <- getTyVar_maybe (last (tyConAppArgs (dataConOrigResTy con)))
1419 , tv `elem` dataConUnivTyVars con
1420 , not (tv `elemVarSet` tyVarsOfTypes (dataConTheta con))
1421 = IsValid -- See Note [Check that the type variable is truly universal]
1422 | otherwise
1423 = NotValid (badCon con existential)
1424
1425 ft_check :: DataCon -> FFoldType Validity
1426 ft_check con = FT { ft_triv = IsValid, ft_var = IsValid
1427 , ft_co_var = NotValid (badCon con covariant)
1428 , ft_fun = \x y -> if allowFunctions then x `andValid` y
1429 else NotValid (badCon con functions)
1430 , ft_tup = \_ xs -> allValid xs
1431 , ft_ty_app = \_ x -> x
1432 , ft_bad_app = NotValid (badCon con wrong_arg)
1433 , ft_forall = \_ x -> x }
1434
1435 existential = ptext (sLit "must be truly polymorphic in the last argument of the data type")
1436 covariant = ptext (sLit "must not use the type variable in a function argument")
1437 functions = ptext (sLit "must not contain function types")
1438 wrong_arg = ptext (sLit "must use the type variable only as the last argument of a data type")
1439
1440 checkFlag :: ExtensionFlag -> Condition
1441 checkFlag flag (dflags, _, _)
1442 | xopt flag dflags = IsValid
1443 | otherwise = NotValid why
1444 where
1445 why = ptext (sLit "You need ") <> text flag_str
1446 <+> ptext (sLit "to derive an instance for this class")
1447 flag_str = case [ flagSpecName f | f <- xFlags , flagSpecFlag f == flag ] of
1448 [s] -> s
1449 other -> pprPanic "checkFlag" (ppr other)
1450
1451 std_class_via_coercible :: Class -> Bool
1452 -- These standard classes can be derived for a newtype
1453 -- using the coercible trick *even if no -XGeneralizedNewtypeDeriving
1454 -- because giving so gives the same results as generating the boilerplate
1455 std_class_via_coercible clas
1456 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
1457 -- Not Read/Show because they respect the type
1458 -- Not Enum, because newtypes are never in Enum
1459
1460
1461 non_coercible_class :: Class -> Bool
1462 -- *Never* derive Read, Show, Typeable, Data, Generic, Generic1 by Coercible,
1463 -- even with -XGeneralizedNewtypeDeriving
1464 -- Also, avoid Traversable, as the Coercible-derived instance and the "normal"-derived
1465 -- instance behave differently if there's a non-lawful Applicative out there.
1466 -- Besides, with roles, Coercible-deriving Traversable is ill-roled.
1467 non_coercible_class cls
1468 = classKey cls `elem` ([ readClassKey, showClassKey, dataClassKey
1469 , genClassKey, gen1ClassKey, typeableClassKey
1470 , traversableClassKey ])
1471
1472 new_dfun_name :: Class -> TyCon -> TcM Name
1473 new_dfun_name clas tycon -- Just a simple wrapper
1474 = do { loc <- getSrcSpanM -- The location of the instance decl, not of the tycon
1475 ; newDFunName clas [mkTyConApp tycon []] loc }
1476 -- The type passed to newDFunName is only used to generate
1477 -- a suitable string; hence the empty type arg list
1478
1479 badCon :: DataCon -> SDoc -> SDoc
1480 badCon con msg = ptext (sLit "Constructor") <+> quotes (ppr con) <+> msg
1481
1482 {-
1483 Note [Check that the type variable is truly universal]
1484 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1485 For Functor, Foldable, Traversable, we must check that the *last argument*
1486 of the type constructor is used truly universally quantified. Example
1487
1488 data T a b where
1489 T1 :: a -> b -> T a b -- Fine! Vanilla H-98
1490 T2 :: b -> c -> T a b -- Fine! Existential c, but we can still map over 'b'
1491 T3 :: b -> T Int b -- Fine! Constraint 'a', but 'b' is still polymorphic
1492 T4 :: Ord b => b -> T a b -- No! 'b' is constrained
1493 T5 :: b -> T b b -- No! 'b' is constrained
1494 T6 :: T a (b,b) -- No! 'b' is constrained
1495
1496 Notice that only the first of these constructors is vanilla H-98. We only
1497 need to take care about the last argument (b in this case). See Trac #8678.
1498 Eg. for T1-T3 we can write
1499
1500 fmap f (T1 a b) = T1 a (f b)
1501 fmap f (T2 b c) = T2 (f b) c
1502 fmap f (T3 x) = T3 (f x)
1503
1504
1505 Note [Superclasses of derived instance]
1506 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1507 In general, a derived instance decl needs the superclasses of the derived
1508 class too. So if we have
1509 data T a = ...deriving( Ord )
1510 then the initial context for Ord (T a) should include Eq (T a). Often this is
1511 redundant; we'll also generate an Ord constraint for each constructor argument,
1512 and that will probably generate enough constraints to make the Eq (T a) constraint
1513 be satisfied too. But not always; consider:
1514
1515 data S a = S
1516 instance Eq (S a)
1517 instance Ord (S a)
1518
1519 data T a = MkT (S a) deriving( Ord )
1520 instance Num a => Eq (T a)
1521
1522 The derived instance for (Ord (T a)) must have a (Num a) constraint!
1523 Similarly consider:
1524 data T a = MkT deriving( Data, Typeable )
1525 Here there *is* no argument field, but we must nevertheless generate
1526 a context for the Data instances:
1527 instance Typable a => Data (T a) where ...
1528
1529
1530 ************************************************************************
1531 * *
1532 Deriving newtypes
1533 * *
1534 ************************************************************************
1535 -}
1536
1537 mkNewTypeEqn :: DynFlags -> Maybe OverlapMode -> [Var] -> Class
1538 -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
1539 -> DerivContext
1540 -> TcRn EarlyDerivSpec
1541 mkNewTypeEqn dflags overlap_mode tvs
1542 cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
1543 -- Want: instance (...) => cls (cls_tys ++ [tycon tc_args]) where ...
1544 | ASSERT( length cls_tys + 1 == classArity cls )
1545 might_derive_via_coercible && ((newtype_deriving && not deriveAnyClass)
1546 || std_class_via_coercible cls)
1547 = do traceTc "newtype deriving:" (ppr tycon <+> ppr rep_tys <+> ppr all_preds)
1548 dfun_name <- new_dfun_name cls tycon
1549 loc <- getSrcSpanM
1550 case mtheta of
1551 Just theta -> return $ GivenTheta $ DS
1552 { ds_loc = loc
1553 , ds_name = dfun_name, ds_tvs = varSetElemsKvsFirst dfun_tvs
1554 , ds_cls = cls, ds_tys = inst_tys
1555 , ds_tc = rep_tycon, ds_tc_args = rep_tc_args
1556 , ds_theta = theta
1557 , ds_overlap = overlap_mode
1558 , ds_newtype = True }
1559 Nothing -> return $ InferTheta $ DS
1560 { ds_loc = loc
1561 , ds_name = dfun_name, ds_tvs = varSetElemsKvsFirst dfun_tvs
1562 , ds_cls = cls, ds_tys = inst_tys
1563 , ds_tc = rep_tycon, ds_tc_args = rep_tc_args
1564 , ds_theta = all_preds
1565 , ds_overlap = overlap_mode
1566 , ds_newtype = True }
1567 | otherwise
1568 = case checkSideConditions dflags mtheta cls cls_tys rep_tycon rep_tc_args of
1569 -- Error with standard class
1570 DerivableClassError msg
1571 | might_derive_via_coercible -> bale_out (msg $$ suggest_nd)
1572 | otherwise -> bale_out msg
1573 -- Must use newtype deriving or DeriveAnyClass
1574 NonDerivableClass _msg
1575 -- Too hard, even with newtype deriving
1576 | newtype_deriving -> bale_out cant_derive_err
1577 -- Try newtype deriving!
1578 | might_derive_via_coercible -> bale_out (non_std $$ suggest_nd)
1579 | otherwise -> bale_out non_std
1580 -- CanDerive/DerivableViaInstance
1581 _ -> do when (newtype_deriving && deriveAnyClass) $
1582 addWarnTc (sep [ ptext (sLit "Both DeriveAnyClass and GeneralizedNewtypeDeriving are enabled")
1583 , ptext (sLit "Defaulting to the DeriveAnyClass strategy for instantiating") <+> ppr cls ])
1584 go_for_it
1585 where
1586 newtype_deriving = xopt Opt_GeneralizedNewtypeDeriving dflags
1587 deriveAnyClass = xopt Opt_DeriveAnyClass dflags
1588 go_for_it = mk_data_eqn overlap_mode tvs cls tycon tc_args
1589 rep_tycon rep_tc_args mtheta
1590 bale_out = bale_out' newtype_deriving
1591 bale_out' b = failWithTc . derivingThingErr b cls cls_tys inst_ty
1592
1593 non_std = nonStdErr cls
1594 suggest_nd = ptext (sLit "Try GeneralizedNewtypeDeriving for GHC's newtype-deriving extension")
1595
1596 -- Here is the plan for newtype derivings. We see
1597 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
1598 -- where t is a type,
1599 -- ak+1...an is a suffix of a1..an, and are all tyars
1600 -- ak+1...an do not occur free in t, nor in the s1..sm
1601 -- (C s1 ... sm) is a *partial applications* of class C
1602 -- with the last parameter missing
1603 -- (T a1 .. ak) matches the kind of C's last argument
1604 -- (and hence so does t)
1605 -- The latter kind-check has been done by deriveTyData already,
1606 -- and tc_args are already trimmed
1607 --
1608 -- We generate the instance
1609 -- instance forall ({a1..ak} u fvs(s1..sm)).
1610 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
1611 -- where T a1...ap is the partial application of
1612 -- the LHS of the correct kind and p >= k
1613 --
1614 -- NB: the variables below are:
1615 -- tc_tvs = [a1, ..., an]
1616 -- tyvars_to_keep = [a1, ..., ak]
1617 -- rep_ty = t ak .. an
1618 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
1619 -- tys = [s1, ..., sm]
1620 -- rep_fn' = t
1621 --
1622 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
1623 -- We generate the instance
1624 -- instance Monad (ST s) => Monad (T s) where
1625
1626 nt_eta_arity = length (fst (newTyConEtadRhs rep_tycon))
1627 -- For newtype T a b = MkT (S a a b), the TyCon machinery already
1628 -- eta-reduces the representation type, so we know that
1629 -- T a ~ S a a
1630 -- That's convenient here, because we may have to apply
1631 -- it to fewer than its original complement of arguments
1632
1633 -- Note [Newtype representation]
1634 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1635 -- Need newTyConRhs (*not* a recursive representation finder)
1636 -- to get the representation type. For example
1637 -- newtype B = MkB Int
1638 -- newtype A = MkA B deriving( Num )
1639 -- We want the Num instance of B, *not* the Num instance of Int,
1640 -- when making the Num instance of A!
1641 rep_inst_ty = newTyConInstRhs rep_tycon rep_tc_args
1642 rep_tys = cls_tys ++ [rep_inst_ty]
1643 rep_pred = mkClassPred cls rep_tys
1644 rep_pred_o = mkPredOrigin DerivOrigin rep_pred
1645 -- rep_pred is the representation dictionary, from where
1646 -- we are gong to get all the methods for the newtype
1647 -- dictionary
1648
1649
1650 -- Next we figure out what superclass dictionaries to use
1651 -- See Note [Newtype deriving superclasses] above
1652
1653 cls_tyvars = classTyVars cls
1654 dfun_tvs = tyVarsOfTypes inst_tys
1655 inst_ty = mkTyConApp tycon tc_args
1656 inst_tys = cls_tys ++ [inst_ty]
1657 sc_theta =
1658 mkThetaOrigin DerivOrigin $
1659 substTheta (zipOpenTvSubst cls_tyvars inst_tys) (classSCTheta cls)
1660
1661
1662 -- Next we collect Coercible constaints between
1663 -- the Class method types, instantiated with the representation and the
1664 -- newtype type; precisely the constraints required for the
1665 -- calls to coercible that we are going to generate.
1666 coercible_constraints =
1667 [ let (Pair t1 t2) = mkCoerceClassMethEqn cls (varSetElemsKvsFirst dfun_tvs) inst_tys rep_inst_ty meth
1668 in mkPredOrigin (DerivOriginCoerce meth t1 t2) (mkCoerciblePred t1 t2)
1669 | meth <- classMethods cls ]
1670
1671 -- If there are no tyvars, there's no need
1672 -- to abstract over the dictionaries we need
1673 -- Example: newtype T = MkT Int deriving( C )
1674 -- We get the derived instance
1675 -- instance C T
1676 -- rather than
1677 -- instance C Int => C T
1678 all_preds = rep_pred_o : coercible_constraints ++ sc_theta -- NB: rep_pred comes first
1679
1680 -------------------------------------------------------------------
1681 -- Figuring out whether we can only do this newtype-deriving thing
1682
1683 -- See Note [Determining whether newtype-deriving is appropriate]
1684 might_derive_via_coercible
1685 = not (non_coercible_class cls)
1686 && eta_ok
1687 && ats_ok
1688 -- && not (isRecursiveTyCon tycon) -- Note [Recursive newtypes]
1689
1690 -- Check that eta reduction is OK
1691 eta_ok = nt_eta_arity <= length rep_tc_args
1692 -- The newtype can be eta-reduced to match the number
1693 -- of type argument actually supplied
1694 -- newtype T a b = MkT (S [a] b) deriving( Monad )
1695 -- Here the 'b' must be the same in the rep type (S [a] b)
1696 -- And the [a] must not mention 'b'. That's all handled
1697 -- by nt_eta_rity.
1698
1699 ats_ok = null (classATs cls)
1700 -- No associated types for the class, because we don't
1701 -- currently generate type 'instance' decls; and cannot do
1702 -- so for 'data' instance decls
1703
1704 cant_derive_err
1705 = vcat [ ppUnless eta_ok eta_msg
1706 , ppUnless ats_ok ats_msg ]
1707 eta_msg = ptext (sLit "cannot eta-reduce the representation type enough")
1708 ats_msg = ptext (sLit "the class has associated types")
1709
1710 {-
1711 Note [Recursive newtypes]
1712 ~~~~~~~~~~~~~~~~~~~~~~~~~
1713 Newtype deriving works fine, even if the newtype is recursive.
1714 e.g. newtype S1 = S1 [T1 ()]
1715 newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
1716 Remember, too, that type families are currently (conservatively) given
1717 a recursive flag, so this also allows newtype deriving to work
1718 for type famillies.
1719
1720 We used to exclude recursive types, because we had a rather simple
1721 minded way of generating the instance decl:
1722 newtype A = MkA [A]
1723 instance Eq [A] => Eq A -- Makes typechecker loop!
1724 But now we require a simple context, so it's ok.
1725
1726 Note [Determining whether newtype-deriving is appropriate]
1727 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1728 When we see
1729 newtype NT = MkNT Foo
1730 deriving C
1731 we have to decide how to perform the deriving. Do we do newtype deriving,
1732 or do we do normal deriving? In general, we prefer to do newtype deriving
1733 wherever possible. So, we try newtype deriving unless there's a glaring
1734 reason not to.
1735
1736 Note that newtype deriving might fail, even after we commit to it. This
1737 is because the derived instance uses `coerce`, which must satisfy its
1738 `Coercible` constraint. This is different than other deriving scenarios,
1739 where we're sure that the resulting instance will type-check.
1740
1741 ************************************************************************
1742 * *
1743 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
1744 * *
1745 ************************************************************************
1746
1747 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
1748 terms, which is the final correct RHS for the corresponding original
1749 equation.
1750 \begin{itemize}
1751 \item
1752 Each (k,TyVarTy tv) in a solution constrains only a type
1753 variable, tv.
1754
1755 \item
1756 The (k,TyVarTy tv) pairs in a solution are canonically
1757 ordered by sorting on type varible, tv, (major key) and then class, k,
1758 (minor key)
1759 \end{itemize}
1760 -}
1761
1762 inferInstanceContexts :: [DerivSpec ThetaOrigin] -> TcM [DerivSpec ThetaType]
1763
1764 inferInstanceContexts [] = return []
1765
1766 inferInstanceContexts infer_specs
1767 = do { traceTc "inferInstanceContexts" $ vcat (map pprDerivSpec infer_specs)
1768 ; iterate_deriv 1 initial_solutions }
1769 where
1770 ------------------------------------------------------------------
1771 -- The initial solutions for the equations claim that each
1772 -- instance has an empty context; this solution is certainly
1773 -- in canonical form.
1774 initial_solutions :: [ThetaType]
1775 initial_solutions = [ [] | _ <- infer_specs ]
1776
1777 ------------------------------------------------------------------
1778 -- iterate_deriv calculates the next batch of solutions,
1779 -- compares it with the current one; finishes if they are the
1780 -- same, otherwise recurses with the new solutions.
1781 -- It fails if any iteration fails
1782 iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec ThetaType]
1783 iterate_deriv n current_solns
1784 | n > 20 -- Looks as if we are in an infinite loop
1785 -- This can happen if we have -XUndecidableInstances
1786 -- (See TcSimplify.tcSimplifyDeriv.)
1787 = pprPanic "solveDerivEqns: probable loop"
1788 (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
1789 | otherwise
1790 = do { -- Extend the inst info from the explicit instance decls
1791 -- with the current set of solutions, and simplify each RHS
1792 inst_specs <- zipWithM newDerivClsInst current_solns infer_specs
1793 ; new_solns <- checkNoErrs $
1794 extendLocalInstEnv inst_specs $
1795 mapM gen_soln infer_specs
1796
1797 ; if (current_solns `eqSolution` new_solns) then
1798 return [ spec { ds_theta = soln }
1799 | (spec, soln) <- zip infer_specs current_solns ]
1800 else
1801 iterate_deriv (n+1) new_solns }
1802
1803 eqSolution = eqListBy (eqListBy eqType)
1804
1805 ------------------------------------------------------------------
1806 gen_soln :: DerivSpec ThetaOrigin -> TcM ThetaType
1807 gen_soln (DS { ds_loc = loc, ds_tvs = tyvars
1808 , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
1809 = setSrcSpan loc $
1810 addErrCtxt (derivInstCtxt the_pred) $
1811 do { theta <- simplifyDeriv the_pred tyvars deriv_rhs
1812 -- checkValidInstance tyvars theta clas inst_tys
1813 -- Not necessary; see Note [Exotic derived instance contexts]
1814
1815 ; traceTc "TcDeriv" (ppr deriv_rhs $$ ppr theta)
1816 -- Claim: the result instance declaration is guaranteed valid
1817 -- Hence no need to call:
1818 -- checkValidInstance tyvars theta clas inst_tys
1819 ; return (sortBy cmpType theta) } -- Canonicalise before returning the solution
1820 where
1821 the_pred = mkClassPred clas inst_tys
1822
1823 ------------------------------------------------------------------
1824 newDerivClsInst :: ThetaType -> DerivSpec theta -> TcM ClsInst
1825 newDerivClsInst theta (DS { ds_name = dfun_name, ds_overlap = overlap_mode
1826 , ds_tvs = tvs, ds_cls = clas, ds_tys = tys })
1827 = newClsInst overlap_mode dfun_name tvs theta clas tys
1828
1829 extendLocalInstEnv :: [ClsInst] -> TcM a -> TcM a
1830 -- Add new locally-defined instances; don't bother to check
1831 -- for functional dependency errors -- that'll happen in TcInstDcls
1832 extendLocalInstEnv dfuns thing_inside
1833 = do { env <- getGblEnv
1834 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
1835 env' = env { tcg_inst_env = inst_env' }
1836 ; setGblEnv env' thing_inside }
1837
1838 {-
1839 ***********************************************************************************
1840 * *
1841 * Simplify derived constraints
1842 * *
1843 ***********************************************************************************
1844 -}
1845
1846 simplifyDeriv :: PredType
1847 -> [TyVar]
1848 -> ThetaOrigin -- Wanted
1849 -> TcM ThetaType -- Needed
1850 -- Given instance (wanted) => C inst_ty
1851 -- Simplify 'wanted' as much as possibles
1852 -- Fail if not possible
1853 simplifyDeriv pred tvs theta
1854 = do { (skol_subst, tvs_skols) <- tcInstSkolTyVars tvs -- Skolemize
1855 -- The constraint solving machinery
1856 -- expects *TcTyVars* not TyVars.
1857 -- We use *non-overlappable* (vanilla) skolems
1858 -- See Note [Overlap and deriving]
1859
1860 ; let subst_skol = zipTopTvSubst tvs_skols $ map mkTyVarTy tvs
1861 skol_set = mkVarSet tvs_skols
1862 doc = ptext (sLit "deriving") <+> parens (ppr pred)
1863
1864 ; wanted <- mapM (\(PredOrigin t o) -> newWanted o (substTy skol_subst t)) theta
1865
1866 ; traceTc "simplifyDeriv" $
1867 vcat [ pprTvBndrs tvs $$ ppr theta $$ ppr wanted, doc ]
1868 ; (residual_wanted, _ev_binds1)
1869 <- solveWantedsTcM (mkSimpleWC wanted)
1870 -- Post: residual_wanted are already zonked
1871
1872 ; let (good, bad) = partitionBagWith get_good (wc_simple residual_wanted)
1873 -- See Note [Exotic derived instance contexts]
1874 get_good :: Ct -> Either PredType Ct
1875 get_good ct | validDerivPred skol_set p
1876 , isWantedCt ct = Left p
1877 -- NB: residual_wanted may contain unsolved
1878 -- Derived and we stick them into the bad set
1879 -- so that reportUnsolved may decide what to do with them
1880 | otherwise = Right ct
1881 where p = ctPred ct
1882
1883 -- If we are deferring type errors, simply ignore any insoluble
1884 -- constraints. They'll come up again when we typecheck the
1885 -- generated instance declaration
1886 ; defer <- goptM Opt_DeferTypeErrors
1887 ; unless defer (reportAllUnsolved (residual_wanted { wc_simple = bad }))
1888
1889 ; let min_theta = mkMinimalBySCs (bagToList good)
1890 ; return (substTheta subst_skol min_theta) }
1891
1892 {-
1893 Note [Overlap and deriving]
1894 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1895 Consider some overlapping instances:
1896 data Show a => Show [a] where ..
1897 data Show [Char] where ...
1898
1899 Now a data type with deriving:
1900 data T a = MkT [a] deriving( Show )
1901
1902 We want to get the derived instance
1903 instance Show [a] => Show (T a) where...
1904 and NOT
1905 instance Show a => Show (T a) where...
1906 so that the (Show (T Char)) instance does the Right Thing
1907
1908 It's very like the situation when we're inferring the type
1909 of a function
1910 f x = show [x]
1911 and we want to infer
1912 f :: Show [a] => a -> String
1913
1914 BOTTOM LINE: use vanilla, non-overlappable skolems when inferring
1915 the context for the derived instance.
1916 Hence tcInstSkolTyVars not tcInstSuperSkolTyVars
1917
1918 Note [Exotic derived instance contexts]
1919 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1920 In a 'derived' instance declaration, we *infer* the context. It's a
1921 bit unclear what rules we should apply for this; the Haskell report is
1922 silent. Obviously, constraints like (Eq a) are fine, but what about
1923 data T f a = MkT (f a) deriving( Eq )
1924 where we'd get an Eq (f a) constraint. That's probably fine too.
1925
1926 One could go further: consider
1927 data T a b c = MkT (Foo a b c) deriving( Eq )
1928 instance (C Int a, Eq b, Eq c) => Eq (Foo a b c)
1929
1930 Notice that this instance (just) satisfies the Paterson termination
1931 conditions. Then we *could* derive an instance decl like this:
1932
1933 instance (C Int a, Eq b, Eq c) => Eq (T a b c)
1934 even though there is no instance for (C Int a), because there just
1935 *might* be an instance for, say, (C Int Bool) at a site where we
1936 need the equality instance for T's.
1937
1938 However, this seems pretty exotic, and it's quite tricky to allow
1939 this, and yet give sensible error messages in the (much more common)
1940 case where we really want that instance decl for C.
1941
1942 So for now we simply require that the derived instance context
1943 should have only type-variable constraints.
1944
1945 Here is another example:
1946 data Fix f = In (f (Fix f)) deriving( Eq )
1947 Here, if we are prepared to allow -XUndecidableInstances we
1948 could derive the instance
1949 instance Eq (f (Fix f)) => Eq (Fix f)
1950 but this is so delicate that I don't think it should happen inside
1951 'deriving'. If you want this, write it yourself!
1952
1953 NB: if you want to lift this condition, make sure you still meet the
1954 termination conditions! If not, the deriving mechanism generates
1955 larger and larger constraints. Example:
1956 data Succ a = S a
1957 data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
1958
1959 Note the lack of a Show instance for Succ. First we'll generate
1960 instance (Show (Succ a), Show a) => Show (Seq a)
1961 and then
1962 instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
1963 and so on. Instead we want to complain of no instance for (Show (Succ a)).
1964
1965 The bottom line
1966 ~~~~~~~~~~~~~~~
1967 Allow constraints which consist only of type variables, with no repeats.
1968
1969
1970 ************************************************************************
1971 * *
1972 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
1973 * *
1974 ************************************************************************
1975
1976 After all the trouble to figure out the required context for the
1977 derived instance declarations, all that's left is to chug along to
1978 produce them. They will then be shoved into @tcInstDecls2@, which
1979 will do all its usual business.
1980
1981 There are lots of possibilities for code to generate. Here are
1982 various general remarks.
1983
1984 PRINCIPLES:
1985 \begin{itemize}
1986 \item
1987 We want derived instances of @Eq@ and @Ord@ (both v common) to be
1988 ``you-couldn't-do-better-by-hand'' efficient.
1989
1990 \item
1991 Deriving @Show@---also pretty common--- should also be reasonable good code.
1992
1993 \item
1994 Deriving for the other classes isn't that common or that big a deal.
1995 \end{itemize}
1996
1997 PRAGMATICS:
1998
1999 \begin{itemize}
2000 \item
2001 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
2002
2003 \item
2004 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
2005
2006 \item
2007 We {\em normally} generate code only for the non-defaulted methods;
2008 there are some exceptions for @Eq@ and (especially) @Ord@...
2009
2010 \item
2011 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
2012 constructor's numeric (@Int#@) tag. These are generated by
2013 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
2014 these is around is given by @hasCon2TagFun@.
2015
2016 The examples under the different sections below will make this
2017 clearer.
2018
2019 \item
2020 Much less often (really just for deriving @Ix@), we use a
2021 @_tag2con_<tycon>@ function. See the examples.
2022
2023 \item
2024 We use the renamer!!! Reason: we're supposed to be
2025 producing @LHsBinds Name@ for the methods, but that means
2026 producing correctly-uniquified code on the fly. This is entirely
2027 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
2028 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
2029 the renamer. What a great hack!
2030 \end{itemize}
2031 -}
2032
2033 -- Generate the InstInfo for the required instance paired with the
2034 -- *representation* tycon for that instance,
2035 -- plus any auxiliary bindings required
2036 --
2037 -- Representation tycons differ from the tycon in the instance signature in
2038 -- case of instances for indexed families.
2039 --
2040 genInst :: CommonAuxiliaries
2041 -> DerivSpec ThetaType
2042 -> TcM (InstInfo RdrName, BagDerivStuff, Maybe Name)
2043 genInst comauxs
2044 spec@(DS { ds_tvs = tvs, ds_tc = rep_tycon, ds_tc_args = rep_tc_args
2045 , ds_theta = theta, ds_newtype = is_newtype, ds_tys = tys
2046 , ds_name = dfun_name, ds_cls = clas, ds_loc = loc })
2047 | is_newtype -- See Note [Bindings for Generalised Newtype Deriving]
2048 = do { inst_spec <- newDerivClsInst theta spec
2049 ; traceTc "genInst/is_newtype" (vcat [ppr loc, ppr clas, ppr tvs, ppr tys, ppr rhs_ty])
2050 ; return ( InstInfo
2051 { iSpec = inst_spec
2052 , iBinds = InstBindings
2053 { ib_binds = gen_Newtype_binds loc clas tvs tys rhs_ty
2054 , ib_tyvars = map Var.varName tvs -- Scope over bindings
2055 , ib_pragmas = []
2056 , ib_extensions = [ Opt_ImpredicativeTypes
2057 , Opt_RankNTypes ]
2058 , ib_derived = True } }
2059 , emptyBag
2060 , Just $ getName $ head $ tyConDataCons rep_tycon ) }
2061 -- See Note [Newtype deriving and unused constructors]
2062
2063 | otherwise
2064 = do { (meth_binds, deriv_stuff) <- genDerivStuff loc clas
2065 dfun_name rep_tycon
2066 (lookup rep_tycon comauxs)
2067 ; inst_spec <- newDerivClsInst theta spec
2068 ; traceTc "newder" (ppr inst_spec)
2069 ; let inst_info = InstInfo { iSpec = inst_spec
2070 , iBinds = InstBindings
2071 { ib_binds = meth_binds
2072 , ib_tyvars = map Var.varName tvs
2073 , ib_pragmas = []
2074 , ib_extensions = []
2075 , ib_derived = True } }
2076 ; return ( inst_info, deriv_stuff, Nothing ) }
2077 where
2078 rhs_ty = newTyConInstRhs rep_tycon rep_tc_args
2079
2080 genDerivStuff :: SrcSpan -> Class -> Name -> TyCon
2081 -> Maybe CommonAuxiliary
2082 -> TcM (LHsBinds RdrName, BagDerivStuff)
2083 genDerivStuff loc clas dfun_name tycon comaux_maybe
2084 | let ck = classKey clas
2085 , ck `elem` [genClassKey, gen1ClassKey] -- Special case because monadic
2086 = let gk = if ck == genClassKey then Gen0 else Gen1
2087 -- TODO NSF: correctly identify when we're building Both instead of One
2088 Just metaTyCons = comaux_maybe -- well-guarded by commonAuxiliaries and genInst
2089 in do
2090 (binds, faminst) <- gen_Generic_binds gk tycon metaTyCons (nameModule dfun_name)
2091 return (binds, unitBag (DerivFamInst faminst))
2092
2093 | otherwise -- Non-monadic generators
2094 = do { dflags <- getDynFlags
2095 ; fix_env <- getDataConFixityFun tycon
2096 ; return (genDerivedBinds dflags fix_env clas loc tycon) }
2097
2098 getDataConFixityFun :: TyCon -> TcM (Name -> Fixity)
2099 -- If the TyCon is locally defined, we want the local fixity env;
2100 -- but if it is imported (which happens for standalone deriving)
2101 -- we need to get the fixity env from the interface file
2102 -- c.f. RnEnv.lookupFixity, and Trac #9830
2103 getDataConFixityFun tc
2104 = do { this_mod <- getModule
2105 ; if nameIsLocalOrFrom this_mod name
2106 then do { fix_env <- getFixityEnv
2107 ; return (lookupFixity fix_env) }
2108 else do { iface <- loadInterfaceForName doc name
2109 -- Should already be loaded!
2110 ; return (mi_fix_fn iface . nameOccName) } }
2111 where
2112 name = tyConName tc
2113 doc = ptext (sLit "Data con fixities for") <+> ppr name
2114
2115 {-
2116 Note [Bindings for Generalised Newtype Deriving]
2117 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2118 Consider
2119 class Eq a => C a where
2120 f :: a -> a
2121 newtype N a = MkN [a] deriving( C )
2122 instance Eq (N a) where ...
2123
2124 The 'deriving C' clause generates, in effect
2125 instance (C [a], Eq a) => C (N a) where
2126 f = coerce (f :: [a] -> [a])
2127
2128 This generates a cast for each method, but allows the superclasse to
2129 be worked out in the usual way. In this case the superclass (Eq (N
2130 a)) will be solved by the explicit Eq (N a) instance. We do *not*
2131 create the superclasses by casting the superclass dictionaries for the
2132 representation type.
2133
2134 See the paper "Safe zero-cost coercions for Hsakell".
2135
2136
2137 ************************************************************************
2138 * *
2139 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
2140 * *
2141 ************************************************************************
2142 -}
2143
2144 derivingNullaryErr :: MsgDoc
2145 derivingNullaryErr = ptext (sLit "Cannot derive instances for nullary classes")
2146
2147 derivingKindErr :: TyCon -> Class -> [Type] -> Kind -> MsgDoc
2148 derivingKindErr tc cls cls_tys cls_kind
2149 = hang (ptext (sLit "Cannot derive well-kinded instance of form")
2150 <+> quotes (pprClassPred cls cls_tys <+> parens (ppr tc <+> ptext (sLit "..."))))
2151 2 (ptext (sLit "Class") <+> quotes (ppr cls)
2152 <+> ptext (sLit "expects an argument of kind") <+> quotes (pprKind cls_kind))
2153
2154 derivingEtaErr :: Class -> [Type] -> Type -> MsgDoc
2155 derivingEtaErr cls cls_tys inst_ty
2156 = sep [ptext (sLit "Cannot eta-reduce to an instance of form"),
2157 nest 2 (ptext (sLit "instance (...) =>")
2158 <+> pprClassPred cls (cls_tys ++ [inst_ty]))]
2159
2160 derivingThingErr :: Bool -> Class -> [Type] -> Type -> MsgDoc -> MsgDoc
2161 derivingThingErr newtype_deriving clas tys ty why
2162 = sep [(hang (ptext (sLit "Can't make a derived instance of"))
2163 2 (quotes (ppr pred))
2164 $$ nest 2 extra) <> colon,
2165 nest 2 why]
2166 where
2167 extra | newtype_deriving = ptext (sLit "(even with cunning newtype deriving)")
2168 | otherwise = Outputable.empty
2169 pred = mkClassPred clas (tys ++ [ty])
2170
2171 derivingHiddenErr :: TyCon -> SDoc
2172 derivingHiddenErr tc
2173 = hang (ptext (sLit "The data constructors of") <+> quotes (ppr tc) <+> ptext (sLit "are not all in scope"))
2174 2 (ptext (sLit "so you cannot derive an instance for it"))
2175
2176 standaloneCtxt :: LHsType Name -> SDoc
2177 standaloneCtxt ty = hang (ptext (sLit "In the stand-alone deriving instance for"))
2178 2 (quotes (ppr ty))
2179
2180 derivInstCtxt :: PredType -> MsgDoc
2181 derivInstCtxt pred
2182 = ptext (sLit "When deriving the instance for") <+> parens (ppr pred)