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