Remove the hasGenerics field of TyCon, improve the way the Generics flags is handled...
[ghc-hetmet.git] / compiler / typecheck / TcDeriv.lhs
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 \begin{code}
9 module TcDeriv ( tcDeriving ) where
10
11 #include "HsVersions.h"
12
13 import HsSyn
14 import DynFlags
15
16 import Generics
17 import TcRnMonad
18 import TcEnv
19 import TcClassDcl( tcAddDeclCtxt )      -- Small helper
20 import TcGenDeriv                       -- Deriv stuff
21 import InstEnv
22 import Inst
23 import TcHsType
24 import TcMType
25 import TcSimplify
26
27 import RnBinds
28 import RnEnv
29 import HscTypes
30
31 import Class
32 import Type
33 import Coercion
34 import ErrUtils
35 import MkId
36 import DataCon
37 import Maybes
38 import RdrName
39 import Name
40 import NameSet
41 import TyCon
42 import TcType
43 import BuildTyCl
44 import BasicTypes
45 import Var
46 import VarSet
47 import PrelNames
48 import SrcLoc
49 import UniqSupply
50 import Util
51 import ListSetOps
52 import Outputable
53 import FastString
54 import Bag
55
56 import Control.Monad
57 \end{code}
58
59 %************************************************************************
60 %*                                                                      *
61                 Overview
62 %*                                                                      *
63 %************************************************************************
64
65 Overall plan
66 ~~~~~~~~~~~~
67 1.  Convert the decls (i.e. data/newtype deriving clauses, 
68     plus standalone deriving) to [EarlyDerivSpec]
69
70 2.  Infer the missing contexts for the Left DerivSpecs
71
72 3.  Add the derived bindings, generating InstInfos
73
74
75 \begin{code}
76 -- DerivSpec is purely  local to this module
77 data DerivSpec  = DS { ds_loc     :: SrcSpan 
78                      , ds_orig    :: CtOrigin 
79                      , ds_name    :: Name
80                      , ds_tvs     :: [TyVar] 
81                      , ds_theta   :: ThetaType
82                      , ds_cls     :: Class
83                      , ds_tys     :: [Type]
84                      , ds_tc      :: TyCon
85                      , ds_tc_args :: [Type]
86                      , ds_newtype :: Bool }
87         -- This spec implies a dfun declaration of the form
88         --       df :: forall tvs. theta => C tys
89         -- The Name is the name for the DFun we'll build
90         -- The tyvars bind all the variables in the theta
91         -- For type families, the tycon in 
92         --       in ds_tys is the *family* tycon
93         --       in ds_tc, ds_tc_args is the *representation* tycon
94         -- For non-family tycons, both are the same
95
96         -- ds_newtype = True  <=> Newtype deriving
97         --              False <=> Vanilla deriving
98 \end{code}
99
100 Example:
101
102      newtype instance T [a] = MkT (Tree a) deriving( C s )
103 ==>  
104      axiom T [a] = :RTList a
105      axiom :RTList a = Tree a
106
107      DS { ds_tvs = [a,s], ds_cls = C, ds_tys = [s, T [a]]
108         , ds_tc = :RTList, ds_tc_args = [a]
109         , ds_newtype = True }
110
111 \begin{code}
112 type DerivContext = Maybe ThetaType
113    -- Nothing    <=> Vanilla deriving; infer the context of the instance decl
114    -- Just theta <=> Standalone deriving: context supplied by programmer
115
116 type EarlyDerivSpec = Either DerivSpec DerivSpec
117         -- Left  ds => the context for the instance should be inferred
118         --             In this case ds_theta is the list of all the 
119         --                constraints needed, such as (Eq [a], Eq a)
120         --                The inference process is to reduce this to a 
121         --                simpler form (e.g. Eq a)
122         -- 
123         -- Right ds => the exact context for the instance is supplied 
124         --             by the programmer; it is ds_theta
125
126 pprDerivSpec :: DerivSpec -> SDoc
127 pprDerivSpec (DS { ds_loc = l, ds_name = n, ds_tvs = tvs, 
128                    ds_cls = c, ds_tys = tys, ds_theta = rhs })
129   = parens (hsep [ppr l, ppr n, ppr tvs, ppr c, ppr tys]
130             <+> equals <+> ppr rhs)
131
132 instance Outputable DerivSpec where
133   ppr = pprDerivSpec
134 \end{code}
135
136
137 Inferring missing contexts 
138 ~~~~~~~~~~~~~~~~~~~~~~~~~~
139 Consider
140
141         data T a b = C1 (Foo a) (Bar b)
142                    | C2 Int (T b a)
143                    | C3 (T a a)
144                    deriving (Eq)
145
146 [NOTE: See end of these comments for what to do with 
147         data (C a, D b) => T a b = ...
148 ]
149
150 We want to come up with an instance declaration of the form
151
152         instance (Ping a, Pong b, ...) => Eq (T a b) where
153                 x == y = ...
154
155 It is pretty easy, albeit tedious, to fill in the code "...".  The
156 trick is to figure out what the context for the instance decl is,
157 namely @Ping@, @Pong@ and friends.
158
159 Let's call the context reqd for the T instance of class C at types
160 (a,b, ...)  C (T a b).  Thus:
161
162         Eq (T a b) = (Ping a, Pong b, ...)
163
164 Now we can get a (recursive) equation from the @data@ decl:
165
166         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
167                    u Eq (T b a) u Eq Int        -- From C2
168                    u Eq (T a a)                 -- From C3
169
170 Foo and Bar may have explicit instances for @Eq@, in which case we can
171 just substitute for them.  Alternatively, either or both may have
172 their @Eq@ instances given by @deriving@ clauses, in which case they
173 form part of the system of equations.
174
175 Now all we need do is simplify and solve the equations, iterating to
176 find the least fixpoint.  Notice that the order of the arguments can
177 switch around, as here in the recursive calls to T.
178
179 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
180
181 We start with:
182
183         Eq (T a b) = {}         -- The empty set
184
185 Next iteration:
186         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
187                    u Eq (T b a) u Eq Int        -- From C2
188                    u Eq (T a a)                 -- From C3
189
190         After simplification:
191                    = Eq a u Ping b u {} u {} u {}
192                    = Eq a u Ping b
193
194 Next iteration:
195
196         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
197                    u Eq (T b a) u Eq Int        -- From C2
198                    u Eq (T a a)                 -- From C3
199
200         After simplification:
201                    = Eq a u Ping b
202                    u (Eq b u Ping a)
203                    u (Eq a u Ping a)
204
205                    = Eq a u Ping b u Eq b u Ping a
206
207 The next iteration gives the same result, so this is the fixpoint.  We
208 need to make a canonical form of the RHS to ensure convergence.  We do
209 this by simplifying the RHS to a form in which
210
211         - the classes constrain only tyvars
212         - the list is sorted by tyvar (major key) and then class (minor key)
213         - no duplicates, of course
214
215 So, here are the synonyms for the ``equation'' structures:
216
217
218 Note [Data decl contexts]
219 ~~~~~~~~~~~~~~~~~~~~~~~~~
220 Consider
221
222         data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
223
224 We will need an instance decl like:
225
226         instance (Read a, RealFloat a) => Read (Complex a) where
227           ...
228
229 The RealFloat in the context is because the read method for Complex is bound
230 to construct a Complex, and doing that requires that the argument type is
231 in RealFloat. 
232
233 But this ain't true for Show, Eq, Ord, etc, since they don't construct
234 a Complex; they only take them apart.
235
236 Our approach: identify the offending classes, and add the data type
237 context to the instance decl.  The "offending classes" are
238
239         Read, Enum?
240
241 FURTHER NOTE ADDED March 2002.  In fact, Haskell98 now requires that
242 pattern matching against a constructor from a data type with a context
243 gives rise to the constraints for that context -- or at least the thinned
244 version.  So now all classes are "offending".
245
246 Note [Newtype deriving]
247 ~~~~~~~~~~~~~~~~~~~~~~~
248 Consider this:
249     class C a b
250     instance C [a] Char
251     newtype T = T Char deriving( C [a] )
252
253 Notice the free 'a' in the deriving.  We have to fill this out to 
254     newtype T = T Char deriving( forall a. C [a] )
255
256 And then translate it to:
257     instance C [a] Char => C [a] T where ...
258     
259         
260 Note [Newtype deriving superclasses]
261 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
262 (See also Trac #1220 for an interesting exchange on newtype
263 deriving and superclasses.)
264
265 The 'tys' here come from the partial application in the deriving
266 clause. The last arg is the new instance type.
267
268 We must pass the superclasses; the newtype might be an instance
269 of them in a different way than the representation type
270 E.g.            newtype Foo a = Foo a deriving( Show, Num, Eq )
271 Then the Show instance is not done via isomorphism; it shows
272         Foo 3 as "Foo 3"
273 The Num instance is derived via isomorphism, but the Show superclass
274 dictionary must the Show instance for Foo, *not* the Show dictionary
275 gotten from the Num dictionary. So we must build a whole new dictionary
276 not just use the Num one.  The instance we want is something like:
277      instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
278         (+) = ((+)@a)
279         ...etc...
280 There may be a coercion needed which we get from the tycon for the newtype
281 when the dict is constructed in TcInstDcls.tcInstDecl2
282
283
284 Note [Unused constructors and deriving clauses]
285 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
286 See Trac #3221.  Consider
287    data T = T1 | T2 deriving( Show )
288 Are T1 and T2 unused?  Well, no: the deriving clause expands to mention
289 both of them.  So we gather defs/uses from deriving just like anything else.
290
291 %************************************************************************
292 %*                                                                      *
293 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
294 %*                                                                      *
295 %************************************************************************
296
297 \begin{code}
298 tcDeriving  :: [LTyClDecl Name]  -- All type constructors
299             -> [LInstDecl Name]  -- All instance declarations
300             -> [LDerivDecl Name] -- All stand-alone deriving declarations
301             -> TcM ([InstInfo Name] -- The generated "instance decls"
302                    ,HsValBinds Name -- Extra generated top-level bindings
303                    ,DefUses
304                    ,[TyCon]         -- Extra generated top-level types
305                    ,[TyCon])        -- Extra generated type family instances
306
307 tcDeriving tycl_decls inst_decls deriv_decls
308   = recoverM (return ([], emptyValBindsOut, emptyDUs, [], [])) $
309     do  {       -- Fish the "deriving"-related information out of the TcEnv
310                 -- And make the necessary "equations".
311           is_boot <- tcIsHsBoot
312         ; traceTc "tcDeriving" (ppr is_boot)
313         ; (early_specs, genericsExtras) 
314                 <- makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
315         ; let (repMetaTys, repTyCons, metaInsts) = unzip3 genericsExtras
316
317         ; overlap_flag <- getOverlapFlag
318         ; let (infer_specs, given_specs) = splitEithers early_specs
319         ; insts1 <- mapM (genInst True overlap_flag) given_specs
320
321         ; final_specs <- extendLocalInstEnv (map (iSpec . fst) insts1) $
322                          inferInstanceContexts overlap_flag infer_specs
323
324         ; insts2 <- mapM (genInst False overlap_flag) final_specs
325
326         -- We no longer generate the old generic to/from functions
327         -- from each type declaration, so this is emptyBag
328         ; gen_binds <- return emptyBag -- mkGenericBinds is_boot tycl_decls
329         
330 {-
331          -- Generate the generic Representable0 instances
332          -- from each type declaration
333         ; repInstsMeta <- genGenericRepBinds is_boot tycl_decls
334         
335         ; let repInsts   = concat (map (\(a,_,_) -> a) repInstsMeta)
336               repMetaTys = map (\(_,b,_) -> b) repInstsMeta
337               repTyCons  = map (\(_,_,c) -> c) repInstsMeta
338 -}
339         ; (inst_info, rn_binds, rn_dus)
340                 <- renameDeriv is_boot gen_binds (insts1 ++ insts2 ++ concat metaInsts {- ++ repInsts -})
341
342         ; dflags <- getDOpts
343         ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
344                  (ddump_deriving inst_info rn_binds))
345 {-
346         ; when (not (null inst_info)) $
347           dumpDerivingInfo (ddump_deriving inst_info rn_binds)
348 -}
349         ; return ( inst_info, rn_binds, rn_dus
350                  , concat (map metaTyCons2TyCons repMetaTys), repTyCons) }
351   where
352     ddump_deriving :: [InstInfo Name] -> HsValBinds Name -> SDoc
353     ddump_deriving inst_infos extra_binds
354       = hang (ptext (sLit "Derived instances"))
355            2 (vcat (map (\i -> pprInstInfoDetails i $$ text "") inst_infos)
356               $$ ppr extra_binds)
357
358
359 renameDeriv :: Bool -> LHsBinds RdrName
360             -> [(InstInfo RdrName, DerivAuxBinds)]
361             -> TcM ([InstInfo Name], HsValBinds Name, DefUses)
362 renameDeriv is_boot gen_binds insts
363   | is_boot     -- If we are compiling a hs-boot file, don't generate any derived bindings
364                 -- The inst-info bindings will all be empty, but it's easier to
365                 -- just use rn_inst_info to change the type appropriately
366   = do  { (rn_inst_infos, fvs) <- mapAndUnzipM rn_inst_info inst_infos  
367         ; return (rn_inst_infos, emptyValBindsOut, usesOnly (plusFVs fvs)) }
368
369   | otherwise
370   = discardWarnings $    -- Discard warnings about unused bindings etc
371     do  { (rn_gen, dus_gen) <- setOptM Opt_ScopedTypeVariables $  -- Type signatures in patterns 
372                                                                   -- are used in the generic binds
373                                rnTopBinds (ValBindsIn gen_binds [])
374         ; keepAliveSetTc (duDefs dus_gen)       -- Mark these guys to be kept alive
375
376                 -- Generate and rename any extra not-one-inst-decl-specific binds, 
377                 -- notably "con2tag" and/or "tag2con" functions.  
378                 -- Bring those names into scope before renaming the instances themselves
379         ; loc <- getSrcSpanM    -- Generic loc for shared bindings
380         ; let (aux_binds, aux_sigs) = unzip $ map (genAuxBind loc) $ 
381                                       rm_dups [] $ concat deriv_aux_binds
382               aux_val_binds = ValBindsIn (listToBag aux_binds) aux_sigs
383         ; rn_aux_lhs <- rnTopBindsLHS emptyFsEnv aux_val_binds
384         ; bindLocalNames (collectHsValBinders rn_aux_lhs) $ 
385     do  { (rn_aux, dus_aux) <- rnTopBindsRHS rn_aux_lhs
386         ; (rn_inst_infos, fvs_insts) <- mapAndUnzipM rn_inst_info inst_infos
387         ; return (rn_inst_infos, rn_aux `plusHsValBinds` rn_gen,
388                   dus_gen `plusDU` dus_aux `plusDU` usesOnly (plusFVs fvs_insts)) } }
389
390   where
391     (inst_infos, deriv_aux_binds) = unzip insts
392     
393         -- Remove duplicate requests for auxilliary bindings
394     rm_dups acc [] = acc
395     rm_dups acc (b:bs) | any (isDupAux b) acc = rm_dups acc bs
396                        | otherwise            = rm_dups (b:acc) bs
397
398
399     rn_inst_info :: InstInfo RdrName -> TcM (InstInfo Name, FreeVars)
400     rn_inst_info info@(InstInfo { iBinds = NewTypeDerived coi tc })
401         = return ( info { iBinds = NewTypeDerived coi tc }
402                  , mkFVs (map dataConName (tyConDataCons tc)))
403           -- See Note [Newtype deriving and unused constructors]
404
405     rn_inst_info inst_info@(InstInfo { iSpec = inst, iBinds = VanillaInst binds sigs standalone_deriv })
406         =       -- Bring the right type variables into 
407                 -- scope (yuk), and rename the method binds
408            ASSERT( null sigs )
409            bindLocalNames (map Var.varName tyvars) $
410            do { (rn_binds, fvs) <- rnMethodBinds clas_nm (\_ -> []) [] binds
411               ; let binds' = VanillaInst rn_binds [] standalone_deriv
412               ; return (inst_info { iBinds = binds' }, fvs) }
413         where
414           (tyvars,_, clas,_) = instanceHead inst
415           clas_nm            = className clas
416
417 -----------------------------------------
418 {- Now unused 
419 mkGenericBinds :: Bool -> [LTyClDecl Name] -> TcM (LHsBinds RdrName)
420 mkGenericBinds is_boot tycl_decls
421   | is_boot 
422   = return emptyBag
423   | otherwise
424   = do  { tcs <- mapM tcLookupTyCon [ tcdName d 
425                                     | L _ d <- tycl_decls, isDataDecl d ]
426         ; return (unionManyBags [ mkTyConGenericBinds tc
427                                 | tc <- tcs, tyConHasGenerics tc ]) }
428                 -- We are only interested in the data type declarations,
429                 -- and then only in the ones whose 'has-generics' flag is on
430                 -- The predicate tyConHasGenerics finds both of these
431 -}
432 \end{code}
433
434 Note [Newtype deriving and unused constructors]
435 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
436 Consider this (see Trac #1954):
437
438   module Bug(P) where
439   newtype P a = MkP (IO a) deriving Monad
440
441 If you compile with -fwarn-unused-binds you do not expect the warning
442 "Defined but not used: data consructor MkP". Yet the newtype deriving
443 code does not explicitly mention MkP, but it should behave as if you
444 had written
445   instance Monad P where
446      return x = MkP (return x)
447      ...etc...
448
449 So we want to signal a user of the data constructor 'MkP'.  That's
450 what we do in rn_inst_info, and it's the only reason we have the TyCon
451 stored in NewTypeDerived.
452
453
454 %************************************************************************
455 %*                                                                      *
456                 From HsSyn to DerivSpec
457 %*                                                                      *
458 %************************************************************************
459
460 @makeDerivSpecs@ fishes around to find the info about needed derived instances.
461
462 \begin{code}
463 -- Make the EarlyDerivSpec for Representable0
464 mkGenDerivSpec :: TyCon -> TcRn (EarlyDerivSpec)
465 mkGenDerivSpec tc = do
466         { cls           <- tcLookupClass rep0ClassName
467         ; let tc_tvs    = tyConTyVars tc
468         ; let tc_app    = mkTyConApp tc (mkTyVarTys tc_tvs)
469         ; let cls_tys   = []
470         ; let mtheta    = Just []
471         ; ds <- mkEqnHelp StandAloneDerivOrigin tc_tvs cls cls_tys tc_app mtheta
472         -- JPM TODO: StandAloneDerivOrigin?...
473         ; {- pprTrace "mkGenDerivSpec" (ppr (tc, ds)) $ -} return ds }
474
475 -- Make the "extras" for the generic representation
476 mkGenDerivExtras :: TyCon 
477                  -> TcRn (MetaTyCons, TyCon, [(InstInfo RdrName, DerivAuxBinds)])
478 mkGenDerivExtras tc = do
479         { (metaTyCons, rep0TyInst) <- genGenericRepExtras tc
480         ; metaInsts                <- genDtMeta (tc, metaTyCons)
481         ; return (metaTyCons, rep0TyInst, metaInsts) }
482
483 makeDerivSpecs :: Bool 
484                -> [LTyClDecl Name] 
485                -> [LInstDecl Name]
486                -> [LDerivDecl Name] 
487                -> TcM ( [EarlyDerivSpec]
488                       , [(MetaTyCons, TyCon, [(InstInfo RdrName, DerivAuxBinds)])])
489 makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
490   | is_boot     -- No 'deriving' at all in hs-boot files
491   = do  { mapM_ add_deriv_err deriv_locs 
492         ; return ([],[]) }
493   | otherwise
494   = do  { eqns1 <- mapAndRecoverM deriveTyData all_tydata
495         ; eqns2 <- mapAndRecoverM deriveStandalone deriv_decls
496         -- Generate EarlyDerivSpec's for Representable, if asked for
497         ; (xGenerics, xDeriveRepresentable) <- genericsFlags
498         ; let allTyNames = [ tcdName d | L _ d <- tycl_decls, isDataDecl d ]
499         ; allTyDecls <- mapM tcLookupTyCon allTyNames
500         -- Select only those types that derive Representable
501         ; let sel_tydata = [ tcdName t | (L _ c, L _ t) <- all_tydata
502                                        , getClassName c == Just rep0ClassName ]
503         ; let sel_deriv_decls = catMaybes [ getTypeName t
504                                   | L _ (DerivDecl (L _ t)) <- deriv_decls
505                                   , getClassName t == Just rep0ClassName ] 
506         ; derTyDecls <- mapM tcLookupTyCon $ 
507                          filter (needsExtras xDeriveRepresentable
508                                   (sel_tydata ++ sel_deriv_decls)) allTyNames
509         -- We need to generate the extras to add to what has
510         -- already been derived
511         ; generic_extras_deriv <- mapM mkGenDerivExtras derTyDecls
512         -- For the remaining types, if Generics is on, we need to
513         -- generate both the instances and the extras, but only for the
514         -- types we can represent.
515         ; let repTyDecls = filter canDoGenerics allTyDecls
516         ; let remTyDecls = filter (\x -> not (x `elem` derTyDecls)) repTyDecls
517         ; generic_instances    <- if xGenerics
518                                    then mapM mkGenDerivSpec   remTyDecls
519                                     else return []
520         ; generic_extras_flag  <- if xGenerics
521                                    then mapM mkGenDerivExtras remTyDecls
522                                     else return []
523         -- Merge and return everything
524         ; {- pprTrace "allTyDecls" (ppr allTyDecls) $ 
525           pprTrace "derTyDecls" (ppr derTyDecls) $ 
526           pprTrace "repTyDecls" (ppr repTyDecls) $ 
527           pprTrace "remTyDecls" (ppr remTyDecls) $ 
528           pprTrace "xGenerics"  (ppr xGenerics) $ 
529           pprTrace "xDeriveRep" (ppr xDeriveRepresentable) $ 
530           pprTrace "all_tydata" (ppr all_tydata) $ 
531           pprTrace "eqns1" (ppr eqns1) $ 
532           pprTrace "eqns2" (ppr eqns2) $ 
533 -}
534           return ( eqns1 ++ eqns2 ++ generic_instances
535                  , generic_extras_deriv ++ generic_extras_flag) }
536   where
537     needsExtras xDeriveRepresentable tydata tc_name = 
538       -- We need extras if the flag DeriveGenerics is on and this type is 
539       -- deriving Representable
540       xDeriveRepresentable && tc_name `elem` tydata
541
542     -- Extracts the name of the class in the deriving
543     getClassName :: HsType Name -> Maybe Name
544     getClassName (HsPredTy (HsClassP n _)) = Just n
545     getClassName _                         = Nothing
546
547     -- Extracts the name of the type in the deriving
548     getTypeName :: HsType Name -> Maybe Name
549     getTypeName (HsPredTy (HsClassP _ [L _ (HsTyVar n)])) = Just n
550     getTypeName _                                         = Nothing
551
552     extractTyDataPreds decls
553       = [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
554
555     all_tydata :: [(LHsType Name, LTyClDecl Name)]
556         -- Derived predicate paired with its data type declaration
557     all_tydata = extractTyDataPreds (instDeclATs inst_decls ++ tycl_decls)
558
559     deriv_locs = map (getLoc . snd) all_tydata
560                  ++ map getLoc deriv_decls
561
562     add_deriv_err loc = setSrcSpan loc $
563                         addErr (hang (ptext (sLit "Deriving not permitted in hs-boot file"))
564                                    2 (ptext (sLit "Use an instance declaration instead")))
565
566 genericsFlags :: TcM (Bool, Bool)
567 genericsFlags = do dOpts <- getDOpts
568                    return ( xopt Opt_Generics            dOpts
569                           , xopt Opt_DeriveRepresentable dOpts)
570
571 ------------------------------------------------------------------
572 deriveStandalone :: LDerivDecl Name -> TcM EarlyDerivSpec
573 -- Standalone deriving declarations
574 --  e.g.   deriving instance Show a => Show (T a)
575 -- Rather like tcLocalInstDecl
576 deriveStandalone (L loc (DerivDecl deriv_ty))
577   = setSrcSpan loc                   $
578     addErrCtxt (standaloneCtxt deriv_ty)  $
579     do { traceTc "Standalone deriving decl for" (ppr deriv_ty)
580        ; (tvs, theta, cls, inst_tys) <- tcHsInstHead deriv_ty
581        ; traceTc "Standalone deriving;" $ vcat
582               [ text "tvs:" <+> ppr tvs
583               , text "theta:" <+> ppr theta
584               , text "cls:" <+> ppr cls
585               , text "tys:" <+> ppr inst_tys ]
586        ; checkValidInstance deriv_ty tvs theta cls inst_tys
587                 -- C.f. TcInstDcls.tcLocalInstDecl1
588
589        ; let cls_tys = take (length inst_tys - 1) inst_tys
590              inst_ty = last inst_tys
591        ; traceTc "Standalone deriving:" $ vcat
592               [ text "class:" <+> ppr cls
593               , text "class types:" <+> ppr cls_tys
594               , text "type:" <+> ppr inst_ty ]
595        ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
596                    (Just theta) }
597
598 ------------------------------------------------------------------
599 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM EarlyDerivSpec
600 deriveTyData (L loc deriv_pred, L _ decl@(TyData { tcdLName = L _ tycon_name, 
601                                                    tcdTyVars = tv_names, 
602                                                    tcdTyPats = ty_pats }))
603   = setSrcSpan loc     $        -- Use the location of the 'deriving' item
604     tcAddDeclCtxt decl $
605     do  { (tvs, tc, tc_args) <- get_lhs ty_pats
606         ; tcExtendTyVarEnv tvs $        -- Deriving preds may (now) mention
607                                         -- the type variables for the type constructor
608
609     do  { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
610                 -- The "deriv_pred" is a LHsType to take account of the fact that for
611                 -- newtype deriving we allow deriving (forall a. C [a]).
612
613         -- Given data T a b c = ... deriving( C d ),
614         -- we want to drop type variables from T so that (C d (T a)) is well-kinded
615         ; let cls_tyvars = classTyVars cls
616               kind = tyVarKind (last cls_tyvars)
617               (arg_kinds, _) = splitKindFunTys kind
618               n_args_to_drop = length arg_kinds 
619               n_args_to_keep = tyConArity tc - n_args_to_drop
620               args_to_drop   = drop n_args_to_keep tc_args
621               inst_ty        = mkTyConApp tc (take n_args_to_keep tc_args)
622               inst_ty_kind   = typeKind inst_ty
623               dropped_tvs    = mkVarSet (mapCatMaybes getTyVar_maybe args_to_drop)
624               univ_tvs       = (mkVarSet tvs `extendVarSetList` deriv_tvs)
625                                         `minusVarSet` dropped_tvs
626  
627         -- Check that the result really is well-kinded
628         ; checkTc (n_args_to_keep >= 0 && (inst_ty_kind `eqKind` kind))
629                   (derivingKindErr tc cls cls_tys kind)
630
631         ; checkTc (sizeVarSet dropped_tvs == n_args_to_drop &&           -- (a)
632                    tyVarsOfTypes (inst_ty:cls_tys) `subVarSet` univ_tvs) -- (b)
633                   (derivingEtaErr cls cls_tys inst_ty)
634                 -- Check that 
635                 --  (a) The data type can be eta-reduced; eg reject:
636                 --              data instance T a a = ... deriving( Monad )
637                 --  (b) The type class args do not mention any of the dropped type
638                 --      variables 
639                 --              newtype T a s = ... deriving( ST s )
640
641         -- Type families can't be partially applied
642         -- e.g.   newtype instance T Int a = MkT [a] deriving( Monad )
643         -- Note [Deriving, type families, and partial applications]
644         ; checkTc (not (isFamilyTyCon tc) || n_args_to_drop == 0)
645                   (typeFamilyPapErr tc cls cls_tys inst_ty)
646
647         ; mkEqnHelp DerivOrigin (varSetElems univ_tvs) cls cls_tys inst_ty Nothing } }
648   where
649         -- Tiresomely we must figure out the "lhs", which is awkward for type families
650         -- E.g.   data T a b = .. deriving( Eq )
651         --          Here, the lhs is (T a b)
652         --        data instance TF Int b = ... deriving( Eq )
653         --          Here, the lhs is (TF Int b)
654         -- But if we just look up the tycon_name, we get is the *family*
655         -- tycon, but not pattern types -- they are in the *rep* tycon.
656     get_lhs Nothing     = do { tc <- tcLookupTyCon tycon_name
657                              ; let tvs = tyConTyVars tc
658                              ; return (tvs, tc, mkTyVarTys tvs) }
659     get_lhs (Just pats) = do { let hs_app = nlHsTyConApp tycon_name pats
660                              ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
661                              ; let (tc, tc_args) = tcSplitTyConApp tc_app
662                              ; return (tvs, tc, tc_args) }
663
664 deriveTyData _other
665   = panic "derivTyData" -- Caller ensures that only TyData can happen
666 \end{code}
667
668 Note [Deriving, type families, and partial applications]
669 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
670 When there are no type families, it's quite easy:
671
672     newtype S a = MkS [a]
673     -- :CoS :: S  ~ []  -- Eta-reduced
674
675     instance Eq [a] => Eq (S a)         -- by coercion sym (Eq (:CoS a)) : Eq [a] ~ Eq (S a)
676     instance Monad [] => Monad S        -- by coercion sym (Monad :CoS)  : Monad [] ~ Monad S 
677
678 When type familes are involved it's trickier:
679
680     data family T a b
681     newtype instance T Int a = MkT [a] deriving( Eq, Monad )
682     -- :RT is the representation type for (T Int a)
683     --  :CoF:R1T a :: T Int a ~ :RT a   -- Not eta reduced
684     --  :Co:R1T    :: :RT ~ []          -- Eta-reduced
685
686     instance Eq [a] => Eq (T Int a)     -- easy by coercion
687     instance Monad [] => Monad (T Int)  -- only if we can eta reduce???
688
689 The "???" bit is that we don't build the :CoF thing in eta-reduced form
690 Henc the current typeFamilyPapErr, even though the instance makes sense.
691 After all, we can write it out
692     instance Monad [] => Monad (T Int)  -- only if we can eta reduce???
693       return x = MkT [x]
694       ... etc ...       
695
696 \begin{code}
697 mkEqnHelp :: CtOrigin -> [TyVar] -> Class -> [Type] -> Type
698           -> DerivContext       -- Just    => context supplied (standalone deriving)
699                                 -- Nothing => context inferred (deriving on data decl)
700           -> TcRn EarlyDerivSpec
701 -- Make the EarlyDerivSpec for an instance
702 --      forall tvs. theta => cls (tys ++ [ty])
703 -- where the 'theta' is optional (that's the Maybe part)
704 -- Assumes that this declaration is well-kinded
705
706 mkEqnHelp orig tvs cls cls_tys tc_app mtheta
707   | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
708   , isAlgTyCon tycon    -- Check for functions, primitive types etc
709   = mk_alg_eqn tycon tc_args
710   | otherwise
711   = failWithTc (derivingThingErr False cls cls_tys tc_app
712                (ptext (sLit "The last argument of the instance must be a data or newtype application")))
713
714   where
715      bale_out msg = failWithTc (derivingThingErr False cls cls_tys tc_app msg)
716
717      mk_alg_eqn tycon tc_args
718       | className cls `elem` typeableClassNames
719       = do { dflags <- getDOpts
720            ; case checkTypeableConditions (dflags, tycon) of
721                Just err -> bale_out err
722                Nothing  -> mk_typeable_eqn orig tvs cls tycon tc_args mtheta }
723
724       | isDataFamilyTyCon tycon
725       , length tc_args /= tyConArity tycon
726       = bale_out (ptext (sLit "Unsaturated data family application"))
727
728       | otherwise
729       = do { (rep_tc, rep_tc_args) <- tcLookupDataFamInst tycon tc_args
730                   -- Be careful to test rep_tc here: in the case of families, 
731                   -- we want to check the instance tycon, not the family tycon
732
733            -- For standalone deriving (mtheta /= Nothing), 
734            -- check that all the data constructors are in scope.
735            ; rdr_env <- getGlobalRdrEnv
736            ; let hidden_data_cons = isAbstractTyCon rep_tc || 
737                                     any not_in_scope (tyConDataCons rep_tc)
738                  not_in_scope dc  = null (lookupGRE_Name rdr_env (dataConName dc))
739            ; unless (isNothing mtheta || not hidden_data_cons)
740                     (bale_out (derivingHiddenErr tycon))
741
742            ; dflags <- getDOpts
743            ; if isDataTyCon rep_tc then
744                 mkDataTypeEqn orig dflags tvs cls cls_tys
745                               tycon tc_args rep_tc rep_tc_args mtheta
746              else
747                 mkNewTypeEqn orig dflags tvs cls cls_tys 
748                              tycon tc_args rep_tc rep_tc_args mtheta }
749 \end{code}
750
751
752 %************************************************************************
753 %*                                                                      *
754                 Deriving data types
755 %*                                                                      *
756 %************************************************************************
757
758 \begin{code}
759 mkDataTypeEqn :: CtOrigin
760               -> DynFlags
761               -> [Var]                  -- Universally quantified type variables in the instance
762               -> Class                  -- Class for which we need to derive an instance
763               -> [Type]                 -- Other parameters to the class except the last
764               -> TyCon                  -- Type constructor for which the instance is requested 
765                                         --    (last parameter to the type class)
766               -> [Type]                 -- Parameters to the type constructor
767               -> TyCon                  -- rep of the above (for type families)
768               -> [Type]                 -- rep of the above
769               -> DerivContext        -- Context of the instance, for standalone deriving
770               -> TcRn EarlyDerivSpec    -- Return 'Nothing' if error
771
772 mkDataTypeEqn orig dflags tvs cls cls_tys
773               tycon tc_args rep_tc rep_tc_args mtheta
774   = case checkSideConditions dflags mtheta cls cls_tys rep_tc of
775         -- NB: pass the *representation* tycon to checkSideConditions
776         CanDerive               -> go_for_it
777         NonDerivableClass       -> bale_out (nonStdErr cls)
778         DerivableClassError msg -> bale_out msg
779   where
780     go_for_it    = mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
781     bale_out msg = failWithTc (derivingThingErr False cls cls_tys (mkTyConApp tycon tc_args) msg)
782
783 mk_data_eqn :: CtOrigin -> [TyVar] -> Class 
784             -> TyCon -> [TcType] -> TyCon -> [TcType] -> DerivContext
785             -> TcM EarlyDerivSpec
786 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
787   = do  { dfun_name <- new_dfun_name cls tycon
788         ; loc <- getSrcSpanM
789         ; let inst_tys = [mkTyConApp tycon tc_args]
790               inferred_constraints = inferConstraints tvs cls inst_tys rep_tc rep_tc_args
791               spec = DS { ds_loc = loc, ds_orig = orig
792                         , ds_name = dfun_name, ds_tvs = tvs 
793                         , ds_cls = cls, ds_tys = inst_tys
794                         , ds_tc = rep_tc, ds_tc_args = rep_tc_args
795                         , ds_theta =  mtheta `orElse` inferred_constraints
796                         , ds_newtype = False }
797
798         ; return (if isJust mtheta then Right spec      -- Specified context
799                                    else Left spec) }    -- Infer context
800
801 ----------------------
802 mk_typeable_eqn :: CtOrigin -> [TyVar] -> Class 
803                 -> TyCon -> [TcType] -> DerivContext
804                 -> TcM EarlyDerivSpec
805 mk_typeable_eqn orig tvs cls tycon tc_args mtheta
806         -- The Typeable class is special in several ways
807         --        data T a b = ... deriving( Typeable )
808         -- gives
809         --        instance Typeable2 T where ...
810         -- Notice that:
811         -- 1. There are no constraints in the instance
812         -- 2. There are no type variables either
813         -- 3. The actual class we want to generate isn't necessarily
814         --      Typeable; it depends on the arity of the type
815   | isNothing mtheta    -- deriving on a data type decl
816   = do  { checkTc (cls `hasKey` typeableClassKey)
817                   (ptext (sLit "Use deriving( Typeable ) on a data type declaration"))
818         ; real_cls <- tcLookupClass (typeableClassNames !! tyConArity tycon)
819         ; mk_typeable_eqn orig tvs real_cls tycon [] (Just []) }
820
821   | otherwise           -- standaone deriving
822   = do  { checkTc (null tc_args)
823                   (ptext (sLit "Derived typeable instance must be of form (Typeable") 
824                         <> int (tyConArity tycon) <+> ppr tycon <> rparen)
825         ; dfun_name <- new_dfun_name cls tycon
826         ; loc <- getSrcSpanM
827         ; return (Right $
828                   DS { ds_loc = loc, ds_orig = orig, ds_name = dfun_name, ds_tvs = []
829                      , ds_cls = cls, ds_tys = [mkTyConApp tycon []]
830                      , ds_tc = tycon, ds_tc_args = []
831                      , ds_theta = mtheta `orElse` [], ds_newtype = False })  }
832
833 ----------------------
834 inferConstraints :: [TyVar] -> Class -> [TcType] -> TyCon -> [TcType] -> ThetaType
835 -- Generate a sufficiently large set of constraints that typechecking the
836 -- generated method definitions should succeed.   This set will be simplified
837 -- before being used in the instance declaration
838 inferConstraints _ cls inst_tys rep_tc rep_tc_args
839   -- Representable0 constraints are easy
840   | cls `hasKey` rep0ClassKey
841   = []
842   -- The others are a bit more complicated
843   | otherwise
844   = ASSERT2( equalLength rep_tc_tvs all_rep_tc_args, ppr cls <+> ppr rep_tc )
845     stupid_constraints ++ extra_constraints
846     ++ sc_constraints ++ con_arg_constraints
847   where
848        -- Constraints arising from the arguments of each constructor
849     con_arg_constraints
850       = [ mkClassPred cls [arg_ty] 
851         | data_con <- tyConDataCons rep_tc,
852           arg_ty   <- ASSERT( isVanillaDataCon data_con )
853                         get_constrained_tys $
854                         dataConInstOrigArgTys data_con all_rep_tc_args,
855           not (isUnLiftedType arg_ty) ]
856                 -- No constraints for unlifted types
857                 -- Where they are legal we generate specilised function calls
858
859                 -- For functor-like classes, two things are different
860                 -- (a) We recurse over argument types to generate constraints
861                 --     See Functor examples in TcGenDeriv
862                 -- (b) The rep_tc_args will be one short
863     is_functor_like = getUnique cls `elem` functorLikeClassKeys
864
865     get_constrained_tys :: [Type] -> [Type]
866     get_constrained_tys tys 
867         | is_functor_like = concatMap (deepSubtypesContaining last_tv) tys
868         | otherwise       = tys
869
870     rep_tc_tvs = tyConTyVars rep_tc
871     last_tv = last rep_tc_tvs
872     all_rep_tc_args | is_functor_like = rep_tc_args ++ [mkTyVarTy last_tv]
873                     | otherwise       = rep_tc_args
874
875         -- Constraints arising from superclasses
876         -- See Note [Superclasses of derived instance]
877     sc_constraints = substTheta (zipOpenTvSubst (classTyVars cls) inst_tys)
878                                 (classSCTheta cls)
879
880         -- Stupid constraints
881     stupid_constraints = substTheta subst (tyConStupidTheta rep_tc)
882     subst = zipTopTvSubst rep_tc_tvs all_rep_tc_args
883               
884         -- Extra Data constraints
885         -- The Data class (only) requires that for 
886         --    instance (...) => Data (T t1 t2) 
887         -- IF   t1:*, t2:*
888         -- THEN (Data t1, Data t2) are among the (...) constraints
889         -- Reason: when the IF holds, we generate a method
890         --             dataCast2 f = gcast2 f
891         --         and we need the Data constraints to typecheck the method
892     extra_constraints 
893       | cls `hasKey` dataClassKey
894       , all (isLiftedTypeKind . typeKind) rep_tc_args 
895       = [mkClassPred cls [ty] | ty <- rep_tc_args]
896       | otherwise 
897       = []
898
899 ------------------------------------------------------------------
900 -- Check side conditions that dis-allow derivability for particular classes
901 -- This is *apart* from the newtype-deriving mechanism
902 --
903 -- Here we get the representation tycon in case of family instances as it has
904 -- the data constructors - but we need to be careful to fall back to the
905 -- family tycon (with indexes) in error messages.
906
907 data DerivStatus = CanDerive
908                  | DerivableClassError SDoc     -- Standard class, but can't do it
909                  | NonDerivableClass            -- Non-standard class
910
911 checkSideConditions :: DynFlags -> DerivContext -> Class -> [TcType] -> TyCon -> DerivStatus
912 checkSideConditions dflags mtheta cls cls_tys rep_tc
913   | Just cond <- sideConditions mtheta cls
914   = case (cond (dflags, rep_tc)) of
915         Just err -> DerivableClassError err     -- Class-specific error
916         Nothing  | null cls_tys -> CanDerive    -- All derivable classes are unary, so
917                                                 -- cls_tys (the type args other than last) 
918                                                 -- should be null
919                  | otherwise    -> DerivableClassError ty_args_why      -- e.g. deriving( Eq s )
920   | otherwise = NonDerivableClass       -- Not a standard class
921   where
922     ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "is not a class")
923
924 checkTypeableConditions :: Condition
925 checkTypeableConditions = checkFlag Opt_DeriveDataTypeable `andCond` cond_typeableOK
926
927 nonStdErr :: Class -> SDoc
928 nonStdErr cls = quotes (ppr cls) <+> ptext (sLit "is not a derivable class")
929
930 sideConditions :: DerivContext -> Class -> Maybe Condition
931 sideConditions mtheta cls
932   | cls_key == eqClassKey          = Just cond_std
933   | cls_key == ordClassKey         = Just cond_std
934   | cls_key == showClassKey        = Just cond_std
935   | cls_key == readClassKey        = Just (cond_std `andCond` cond_noUnliftedArgs)
936   | cls_key == enumClassKey        = Just (cond_std `andCond` cond_isEnumeration)
937   | cls_key == ixClassKey          = Just (cond_std `andCond` cond_enumOrProduct)
938   | cls_key == boundedClassKey     = Just (cond_std `andCond` cond_enumOrProduct)
939   | cls_key == dataClassKey        = Just (checkFlag Opt_DeriveDataTypeable `andCond` 
940                                            cond_std `andCond` cond_noUnliftedArgs)
941   | cls_key == functorClassKey     = Just (checkFlag Opt_DeriveFunctor `andCond`
942                                            cond_functorOK True)  -- NB: no cond_std!
943   | cls_key == foldableClassKey    = Just (checkFlag Opt_DeriveFoldable `andCond`
944                                            cond_functorOK False) -- Functor/Fold/Trav works ok for rank-n types
945   | cls_key == traversableClassKey = Just (checkFlag Opt_DeriveTraversable `andCond`
946                                            cond_functorOK False)
947   | cls_key == rep0ClassKey        = Just (cond_RepresentableOk `andCond`
948                                            (checkFlag Opt_DeriveRepresentable `orCond`
949                                             checkFlag Opt_Generics))
950   | otherwise = Nothing
951   where
952     cls_key = getUnique cls
953     cond_std = cond_stdOK mtheta
954
955 type Condition = (DynFlags, TyCon) -> Maybe SDoc
956         -- first Bool is whether or not we are allowed to derive Data and Typeable
957         -- second Bool is whether or not we are allowed to derive Functor
958         -- TyCon is the *representation* tycon if the 
959         --      data type is an indexed one
960         -- Nothing => OK
961
962 orCond :: Condition -> Condition -> Condition
963 orCond c1 c2 tc 
964   = case c1 tc of
965         Nothing -> Nothing          -- c1 succeeds
966         Just x  -> case c2 tc of    -- c1 fails
967                      Nothing -> Nothing
968                      Just y  -> Just (x $$ ptext (sLit "  and") $$ y)
969                                     -- Both fail
970
971 andCond :: Condition -> Condition -> Condition
972 andCond c1 c2 tc = case c1 tc of
973                      Nothing -> c2 tc   -- c1 succeeds
974                      Just x  -> Just x  -- c1 fails
975
976 cond_stdOK :: DerivContext -> Condition
977 cond_stdOK (Just _) _
978   = Nothing     -- Don't check these conservative conditions for
979                 -- standalone deriving; just generate the code
980                 -- and let the typechecker handle the result
981 cond_stdOK Nothing (_, rep_tc)
982   | null data_cons      = Just (no_cons_why rep_tc $$ suggestion)
983   | not (null con_whys) = Just (vcat con_whys $$ suggestion)
984   | otherwise           = Nothing
985   where
986     suggestion  = ptext (sLit "Possible fix: use a standalone deriving declaration instead")
987     data_cons   = tyConDataCons rep_tc
988     con_whys = mapCatMaybes check_con data_cons
989
990     check_con :: DataCon -> Maybe SDoc
991     check_con con 
992       | isVanillaDataCon con
993       , all isTauTy (dataConOrigArgTys con) = Nothing
994       | otherwise = Just (badCon con (ptext (sLit "does not have a Haskell-98 type")))
995   
996 no_cons_why :: TyCon -> SDoc
997 no_cons_why rep_tc = quotes (pprSourceTyCon rep_tc) <+> 
998                      ptext (sLit "has no data constructors")
999
1000 -- JPM TODO: should give better error message
1001 cond_RepresentableOk :: Condition
1002 cond_RepresentableOk (_,t) | canDoGenerics t = Nothing
1003                            | otherwise       = Just (ptext (sLit "Cannot derive Representable for type") <+> ppr t)
1004
1005 cond_enumOrProduct :: Condition
1006 cond_enumOrProduct = cond_isEnumeration `orCond` 
1007                        (cond_isProduct `andCond` cond_noUnliftedArgs)
1008
1009 cond_noUnliftedArgs :: Condition
1010 -- For some classes (eg Eq, Ord) we allow unlifted arg types
1011 -- by generating specilaised code.  For others (eg Data) we don't.
1012 cond_noUnliftedArgs (_, tc)
1013   | null bad_cons = Nothing
1014   | otherwise     = Just why
1015   where
1016     bad_cons = [ con | con <- tyConDataCons tc
1017                      , any isUnLiftedType (dataConOrigArgTys con) ]
1018     why = badCon (head bad_cons) (ptext (sLit "has arguments of unlifted type"))
1019
1020 cond_isEnumeration :: Condition
1021 cond_isEnumeration (_, rep_tc)
1022   | isEnumerationTyCon rep_tc   = Nothing
1023   | otherwise                   = Just why
1024   where
1025     why = sep [ quotes (pprSourceTyCon rep_tc) <+> 
1026                   ptext (sLit "is not an enumeration type")
1027               , ptext (sLit "(an enumeration consists of one or more nullary, non-GADT constructors)") ]
1028                   -- See Note [Enumeration types] in TyCon
1029
1030 cond_isProduct :: Condition
1031 cond_isProduct (_, rep_tc)
1032   | isProductTyCon rep_tc = Nothing
1033   | otherwise             = Just why
1034   where
1035     why = quotes (pprSourceTyCon rep_tc) <+> 
1036           ptext (sLit "does not have precisely one constructor")
1037
1038 cond_typeableOK :: Condition
1039 -- OK for Typeable class
1040 -- Currently: (a) args all of kind *
1041 --            (b) 7 or fewer args
1042 cond_typeableOK (_, tc)
1043   | tyConArity tc > 7 = Just too_many
1044   | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars tc)) 
1045                       = Just bad_kind
1046   | otherwise         = Nothing
1047   where
1048     too_many = quotes (pprSourceTyCon tc) <+> 
1049                ptext (sLit "has too many arguments")
1050     bad_kind = quotes (pprSourceTyCon tc) <+> 
1051                ptext (sLit "has arguments of kind other than `*'")
1052
1053 functorLikeClassKeys :: [Unique]
1054 functorLikeClassKeys = [functorClassKey, foldableClassKey, traversableClassKey]
1055
1056 cond_functorOK :: Bool -> Condition
1057 -- OK for Functor/Foldable/Traversable class
1058 -- Currently: (a) at least one argument
1059 --            (b) don't use argument contravariantly
1060 --            (c) don't use argument in the wrong place, e.g. data T a = T (X a a)
1061 --            (d) optionally: don't use function types
1062 --            (e) no "stupid context" on data type
1063 cond_functorOK allowFunctions (_, rep_tc)
1064   | null tc_tvs
1065   = Just (ptext (sLit "Data type") <+> quotes (ppr rep_tc) 
1066           <+> ptext (sLit "has no parameters"))
1067
1068   | not (null bad_stupid_theta)
1069   = Just (ptext (sLit "Data type") <+> quotes (ppr rep_tc) 
1070           <+> ptext (sLit "has a class context") <+> pprTheta bad_stupid_theta)
1071
1072   | otherwise
1073   = msum (map check_con data_cons)      -- msum picks the first 'Just', if any
1074   where
1075     tc_tvs            = tyConTyVars rep_tc
1076     Just (_, last_tv) = snocView tc_tvs
1077     bad_stupid_theta  = filter is_bad (tyConStupidTheta rep_tc)
1078     is_bad pred       = last_tv `elemVarSet` tyVarsOfPred pred
1079
1080     data_cons = tyConDataCons rep_tc
1081     check_con con = msum (check_vanilla con : foldDataConArgs (ft_check con) con)
1082
1083     check_vanilla :: DataCon -> Maybe SDoc
1084     check_vanilla con | isVanillaDataCon con = Nothing
1085                       | otherwise            = Just (badCon con existential)
1086
1087     ft_check :: DataCon -> FFoldType (Maybe SDoc)
1088     ft_check con = FT { ft_triv = Nothing, ft_var = Nothing
1089                       , ft_co_var = Just (badCon con covariant)
1090                       , ft_fun = \x y -> if allowFunctions then x `mplus` y 
1091                                                            else Just (badCon con functions)
1092                       , ft_tup = \_ xs  -> msum xs
1093                       , ft_ty_app = \_ x   -> x
1094                       , ft_bad_app = Just (badCon con wrong_arg)
1095                       , ft_forall = \_ x   -> x }
1096                     
1097     existential = ptext (sLit "has existential arguments")
1098     covariant   = ptext (sLit "uses the type variable in a function argument")
1099     functions   = ptext (sLit "contains function types")
1100     wrong_arg   = ptext (sLit "uses the type variable in an argument other than the last")
1101
1102 checkFlag :: ExtensionFlag -> Condition
1103 checkFlag flag (dflags, _)
1104   | xopt flag dflags = Nothing
1105   | otherwise        = Just why
1106   where
1107     why = ptext (sLit "You need -X") <> text flag_str 
1108           <+> ptext (sLit "to derive an instance for this class")
1109     flag_str = case [ s | (s, f, _) <- xFlags, f==flag ] of
1110                  [s]   -> s
1111                  other -> pprPanic "checkFlag" (ppr other)
1112
1113 std_class_via_iso :: Class -> Bool
1114 -- These standard classes can be derived for a newtype
1115 -- using the isomorphism trick *even if no -XGeneralizedNewtypeDeriving
1116 -- because giving so gives the same results as generating the boilerplate
1117 std_class_via_iso clas  
1118   = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
1119         -- Not Read/Show because they respect the type
1120         -- Not Enum, because newtypes are never in Enum
1121
1122
1123 non_iso_class :: Class -> Bool
1124 -- *Never* derive Read,Show,Typeable,Data,Representable0 by isomorphism,
1125 -- even with -XGeneralizedNewtypeDeriving
1126 non_iso_class cls 
1127   = classKey cls `elem` ([ readClassKey, showClassKey, dataClassKey
1128                          , rep0ClassKey] ++ typeableClassKeys)
1129
1130 typeableClassKeys :: [Unique]
1131 typeableClassKeys = map getUnique typeableClassNames
1132
1133 new_dfun_name :: Class -> TyCon -> TcM Name
1134 new_dfun_name clas tycon        -- Just a simple wrapper
1135   = do { loc <- getSrcSpanM     -- The location of the instance decl, not of the tycon
1136         ; newDFunName clas [mkTyConApp tycon []] loc }
1137         -- The type passed to newDFunName is only used to generate
1138         -- a suitable string; hence the empty type arg list
1139
1140 badCon :: DataCon -> SDoc -> SDoc
1141 badCon con msg = ptext (sLit "Constructor") <+> quotes (ppr con) <+> msg
1142 \end{code}
1143
1144 Note [Superclasses of derived instance] 
1145 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1146 In general, a derived instance decl needs the superclasses of the derived
1147 class too.  So if we have
1148         data T a = ...deriving( Ord )
1149 then the initial context for Ord (T a) should include Eq (T a).  Often this is 
1150 redundant; we'll also generate an Ord constraint for each constructor argument,
1151 and that will probably generate enough constraints to make the Eq (T a) constraint 
1152 be satisfied too.  But not always; consider:
1153
1154  data S a = S
1155  instance Eq (S a)
1156  instance Ord (S a)
1157
1158  data T a = MkT (S a) deriving( Ord )
1159  instance Num a => Eq (T a)
1160
1161 The derived instance for (Ord (T a)) must have a (Num a) constraint!
1162 Similarly consider:
1163         data T a = MkT deriving( Data, Typeable )
1164 Here there *is* no argument field, but we must nevertheless generate
1165 a context for the Data instances:
1166         instance Typable a => Data (T a) where ...
1167
1168
1169 %************************************************************************
1170 %*                                                                      *
1171                 Deriving newtypes
1172 %*                                                                      *
1173 %************************************************************************
1174
1175 \begin{code}
1176 mkNewTypeEqn :: CtOrigin -> DynFlags -> [Var] -> Class
1177              -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
1178              -> DerivContext
1179              -> TcRn EarlyDerivSpec
1180 mkNewTypeEqn orig dflags tvs
1181              cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
1182 -- Want: instance (...) => cls (cls_tys ++ [tycon tc_args]) where ...
1183   | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
1184   = do  { traceTc "newtype deriving:" (ppr tycon <+> ppr rep_tys <+> ppr all_preds)
1185         ; dfun_name <- new_dfun_name cls tycon
1186         ; loc <- getSrcSpanM
1187         ; let spec = DS { ds_loc = loc, ds_orig = orig
1188                         , ds_name = dfun_name, ds_tvs = varSetElems dfun_tvs 
1189                         , ds_cls = cls, ds_tys = inst_tys
1190                         , ds_tc = rep_tycon, ds_tc_args = rep_tc_args
1191                         , ds_theta =  mtheta `orElse` all_preds
1192                         , ds_newtype = True }
1193         ; return (if isJust mtheta then Right spec
1194                                    else Left spec) }
1195
1196   | otherwise
1197   = case checkSideConditions dflags mtheta cls cls_tys rep_tycon of
1198       CanDerive -> go_for_it    -- Use the standard H98 method
1199       DerivableClassError msg   -- Error with standard class
1200         | can_derive_via_isomorphism -> bale_out (msg $$ suggest_nd)
1201         | otherwise                  -> bale_out msg
1202       NonDerivableClass         -- Must use newtype deriving
1203         | newtype_deriving           -> bale_out cant_derive_err  -- Too hard, even with newtype deriving
1204         | can_derive_via_isomorphism -> bale_out (non_std $$ suggest_nd) -- Try newtype deriving!
1205         | otherwise                  -> bale_out non_std
1206   where
1207         newtype_deriving = xopt Opt_GeneralizedNewtypeDeriving dflags
1208         go_for_it        = mk_data_eqn orig tvs cls tycon tc_args rep_tycon rep_tc_args mtheta
1209         bale_out msg     = failWithTc (derivingThingErr newtype_deriving cls cls_tys inst_ty msg)
1210
1211         non_std    = nonStdErr cls
1212         suggest_nd = ptext (sLit "Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")
1213
1214         -- Here is the plan for newtype derivings.  We see
1215         --        newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
1216         -- where t is a type,
1217         --       ak+1...an is a suffix of a1..an, and are all tyars
1218         --       ak+1...an do not occur free in t, nor in the s1..sm
1219         --       (C s1 ... sm) is a  *partial applications* of class C 
1220         --                      with the last parameter missing
1221         --       (T a1 .. ak) matches the kind of C's last argument
1222         --              (and hence so does t)
1223         -- The latter kind-check has been done by deriveTyData already,
1224         -- and tc_args are already trimmed
1225         --
1226         -- We generate the instance
1227         --       instance forall ({a1..ak} u fvs(s1..sm)).
1228         --                C s1 .. sm t => C s1 .. sm (T a1...ak)
1229         -- where T a1...ap is the partial application of 
1230         --       the LHS of the correct kind and p >= k
1231         --
1232         --      NB: the variables below are:
1233         --              tc_tvs = [a1, ..., an]
1234         --              tyvars_to_keep = [a1, ..., ak]
1235         --              rep_ty = t ak .. an
1236         --              deriv_tvs = fvs(s1..sm) \ tc_tvs
1237         --              tys = [s1, ..., sm]
1238         --              rep_fn' = t
1239         --
1240         -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
1241         -- We generate the instance
1242         --      instance Monad (ST s) => Monad (T s) where 
1243
1244         nt_eta_arity = length (fst (newTyConEtadRhs rep_tycon))
1245                 -- For newtype T a b = MkT (S a a b), the TyCon machinery already
1246                 -- eta-reduces the representation type, so we know that
1247                 --      T a ~ S a a
1248                 -- That's convenient here, because we may have to apply
1249                 -- it to fewer than its original complement of arguments
1250
1251         -- Note [Newtype representation]
1252         -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1253         -- Need newTyConRhs (*not* a recursive representation finder) 
1254         -- to get the representation type. For example
1255         --      newtype B = MkB Int
1256         --      newtype A = MkA B deriving( Num )
1257         -- We want the Num instance of B, *not* the Num instance of Int,
1258         -- when making the Num instance of A!
1259         rep_inst_ty = newTyConInstRhs rep_tycon rep_tc_args
1260         rep_tys     = cls_tys ++ [rep_inst_ty]
1261         rep_pred    = mkClassPred cls rep_tys
1262                 -- rep_pred is the representation dictionary, from where
1263                 -- we are gong to get all the methods for the newtype
1264                 -- dictionary 
1265
1266
1267     -- Next we figure out what superclass dictionaries to use
1268     -- See Note [Newtype deriving superclasses] above
1269
1270         cls_tyvars = classTyVars cls
1271         dfun_tvs = tyVarsOfTypes inst_tys
1272         inst_ty = mkTyConApp tycon tc_args
1273         inst_tys = cls_tys ++ [inst_ty]
1274         sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
1275                               (classSCTheta cls)
1276
1277                 -- If there are no tyvars, there's no need
1278                 -- to abstract over the dictionaries we need
1279                 -- Example:     newtype T = MkT Int deriving( C )
1280                 -- We get the derived instance
1281                 --              instance C T
1282                 -- rather than
1283                 --              instance C Int => C T
1284         all_preds = rep_pred : sc_theta         -- NB: rep_pred comes first
1285
1286         -------------------------------------------------------------------
1287         --  Figuring out whether we can only do this newtype-deriving thing
1288
1289         can_derive_via_isomorphism
1290            =  not (non_iso_class cls)
1291            && arity_ok
1292            && eta_ok
1293            && ats_ok
1294 --         && not (isRecursiveTyCon tycon)      -- Note [Recursive newtypes]
1295
1296         arity_ok = length cls_tys + 1 == classArity cls
1297                 -- Well kinded; eg not: newtype T ... deriving( ST )
1298                 --                      because ST needs *2* type params
1299
1300         -- Check that eta reduction is OK
1301         eta_ok = nt_eta_arity <= length rep_tc_args
1302                 -- The newtype can be eta-reduced to match the number
1303                 --     of type argument actually supplied
1304                 --        newtype T a b = MkT (S [a] b) deriving( Monad )
1305                 --     Here the 'b' must be the same in the rep type (S [a] b)
1306                 --     And the [a] must not mention 'b'.  That's all handled
1307                 --     by nt_eta_rity.
1308
1309         ats_ok = null (classATs cls)    
1310                -- No associated types for the class, because we don't 
1311                -- currently generate type 'instance' decls; and cannot do
1312                -- so for 'data' instance decls
1313                                          
1314         cant_derive_err
1315            = vcat [ ppUnless arity_ok arity_msg
1316                   , ppUnless eta_ok eta_msg
1317                   , ppUnless ats_ok ats_msg ]
1318         arity_msg = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "does not have arity 1")
1319         eta_msg   = ptext (sLit "cannot eta-reduce the representation type enough")
1320         ats_msg   = ptext (sLit "the class has associated types")
1321 \end{code}
1322
1323 Note [Recursive newtypes]
1324 ~~~~~~~~~~~~~~~~~~~~~~~~~
1325 Newtype deriving works fine, even if the newtype is recursive.
1326 e.g.    newtype S1 = S1 [T1 ()]
1327         newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
1328 Remember, too, that type families are curretly (conservatively) given
1329 a recursive flag, so this also allows newtype deriving to work
1330 for type famillies.
1331
1332 We used to exclude recursive types, because we had a rather simple
1333 minded way of generating the instance decl:
1334    newtype A = MkA [A]
1335    instance Eq [A] => Eq A      -- Makes typechecker loop!
1336 But now we require a simple context, so it's ok.
1337
1338
1339 %************************************************************************
1340 %*                                                                      *
1341 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
1342 %*                                                                      *
1343 %************************************************************************
1344
1345 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
1346 terms, which is the final correct RHS for the corresponding original
1347 equation.
1348 \begin{itemize}
1349 \item
1350 Each (k,TyVarTy tv) in a solution constrains only a type
1351 variable, tv.
1352
1353 \item
1354 The (k,TyVarTy tv) pairs in a solution are canonically
1355 ordered by sorting on type varible, tv, (major key) and then class, k,
1356 (minor key)
1357 \end{itemize}
1358
1359 \begin{code}
1360 inferInstanceContexts :: OverlapFlag -> [DerivSpec] -> TcM [DerivSpec]
1361
1362 inferInstanceContexts _ [] = return []
1363
1364 inferInstanceContexts oflag infer_specs
1365   = do  { traceTc "inferInstanceContexts" $ vcat (map pprDerivSpec infer_specs)
1366         ; iterate_deriv 1 initial_solutions }
1367   where
1368     ------------------------------------------------------------------
1369         -- The initial solutions for the equations claim that each
1370         -- instance has an empty context; this solution is certainly
1371         -- in canonical form.
1372     initial_solutions :: [ThetaType]
1373     initial_solutions = [ [] | _ <- infer_specs ]
1374
1375     ------------------------------------------------------------------
1376         -- iterate_deriv calculates the next batch of solutions,
1377         -- compares it with the current one; finishes if they are the
1378         -- same, otherwise recurses with the new solutions.
1379         -- It fails if any iteration fails
1380     iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec]
1381     iterate_deriv n current_solns
1382       | n > 20  -- Looks as if we are in an infinite loop
1383                 -- This can happen if we have -XUndecidableInstances
1384                 -- (See TcSimplify.tcSimplifyDeriv.)
1385       = pprPanic "solveDerivEqns: probable loop" 
1386                  (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
1387       | otherwise
1388       = do {      -- Extend the inst info from the explicit instance decls
1389                   -- with the current set of solutions, and simplify each RHS
1390              let inst_specs = zipWithEqual "add_solns" (mkInstance oflag)
1391                                            current_solns infer_specs
1392            ; new_solns <- checkNoErrs $
1393                           extendLocalInstEnv inst_specs $
1394                           mapM gen_soln infer_specs
1395
1396            ; if (current_solns == new_solns) then
1397                 return [ spec { ds_theta = soln } 
1398                        | (spec, soln) <- zip infer_specs current_solns ]
1399              else
1400                 iterate_deriv (n+1) new_solns }
1401
1402     ------------------------------------------------------------------
1403     gen_soln :: DerivSpec  -> TcM [PredType]
1404     gen_soln (DS { ds_loc = loc, ds_orig = orig, ds_tvs = tyvars 
1405                  , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
1406       = setSrcSpan loc  $
1407         addErrCtxt (derivInstCtxt the_pred) $ 
1408         do {      -- Check for a bizarre corner case, when the derived instance decl should
1409                   -- have form  instance C a b => D (T a) where ...
1410                   -- Note that 'b' isn't a parameter of T.  This gives rise to all sorts
1411                   -- of problems; in particular, it's hard to compare solutions for
1412                   -- equality when finding the fixpoint.  Moreover, simplifyDeriv
1413                   -- has an assert failure because it finds a TyVar when it expects
1414                   -- only TcTyVars.  So I just rule it out for now.  I'm not 
1415                   -- even sure how it can arise.
1416                   
1417            ; let tv_set = mkVarSet tyvars
1418                  weird_preds = [pred | pred <- deriv_rhs
1419                                      , not (tyVarsOfPred pred `subVarSet` tv_set)]  
1420            ; mapM_ (addErrTc . badDerivedPred) weird_preds      
1421
1422            ; theta <- simplifyDeriv orig the_pred tyvars deriv_rhs
1423                 -- checkValidInstance tyvars theta clas inst_tys
1424                 -- Not necessary; see Note [Exotic derived instance contexts]
1425                 --                in TcSimplify
1426                 
1427            ; traceTc "TcDeriv" (ppr deriv_rhs $$ ppr theta)
1428                 -- Claim: the result instance declaration is guaranteed valid
1429                 -- Hence no need to call:
1430                 --   checkValidInstance tyvars theta clas inst_tys
1431            ; return (sortLe (<=) theta) }       -- Canonicalise before returning the solution
1432       where
1433         the_pred = mkClassPred clas inst_tys
1434
1435 ------------------------------------------------------------------
1436 mkInstance :: OverlapFlag -> ThetaType -> DerivSpec -> Instance
1437 mkInstance overlap_flag theta
1438             (DS { ds_name = dfun_name
1439                 , ds_tvs = tyvars, ds_cls = clas, ds_tys = tys })
1440   = mkLocalInstance dfun overlap_flag
1441   where
1442     dfun = mkDictFunId dfun_name tyvars theta clas tys
1443
1444
1445 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
1446 -- Add new locally-defined instances; don't bother to check
1447 -- for functional dependency errors -- that'll happen in TcInstDcls
1448 extendLocalInstEnv dfuns thing_inside
1449  = do { env <- getGblEnv
1450       ; let  inst_env' = extendInstEnvList (tcg_inst_env env) dfuns 
1451              env'      = env { tcg_inst_env = inst_env' }
1452       ; setGblEnv env' thing_inside }
1453 \end{code}
1454
1455
1456 %************************************************************************
1457 %*                                                                      *
1458 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
1459 %*                                                                      *
1460 %************************************************************************
1461
1462 After all the trouble to figure out the required context for the
1463 derived instance declarations, all that's left is to chug along to
1464 produce them.  They will then be shoved into @tcInstDecls2@, which
1465 will do all its usual business.
1466
1467 There are lots of possibilities for code to generate.  Here are
1468 various general remarks.
1469
1470 PRINCIPLES:
1471 \begin{itemize}
1472 \item
1473 We want derived instances of @Eq@ and @Ord@ (both v common) to be
1474 ``you-couldn't-do-better-by-hand'' efficient.
1475
1476 \item
1477 Deriving @Show@---also pretty common--- should also be reasonable good code.
1478
1479 \item
1480 Deriving for the other classes isn't that common or that big a deal.
1481 \end{itemize}
1482
1483 PRAGMATICS:
1484
1485 \begin{itemize}
1486 \item
1487 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
1488
1489 \item
1490 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
1491
1492 \item
1493 We {\em normally} generate code only for the non-defaulted methods;
1494 there are some exceptions for @Eq@ and (especially) @Ord@...
1495
1496 \item
1497 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
1498 constructor's numeric (@Int#@) tag.  These are generated by
1499 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
1500 these is around is given by @hasCon2TagFun@.
1501
1502 The examples under the different sections below will make this
1503 clearer.
1504
1505 \item
1506 Much less often (really just for deriving @Ix@), we use a
1507 @_tag2con_<tycon>@ function.  See the examples.
1508
1509 \item
1510 We use the renamer!!!  Reason: we're supposed to be
1511 producing @LHsBinds Name@ for the methods, but that means
1512 producing correctly-uniquified code on the fly.  This is entirely
1513 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
1514 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
1515 the renamer.  What a great hack!
1516 \end{itemize}
1517
1518 \begin{code}
1519 -- Generate the InstInfo for the required instance paired with the
1520 --   *representation* tycon for that instance,
1521 -- plus any auxiliary bindings required
1522 --
1523 -- Representation tycons differ from the tycon in the instance signature in
1524 -- case of instances for indexed families.
1525 --
1526 genInst :: Bool         -- True <=> standalone deriving
1527         -> OverlapFlag
1528         -> DerivSpec -> TcM (InstInfo RdrName, DerivAuxBinds)
1529 genInst standalone_deriv oflag
1530         spec@(DS { ds_tc = rep_tycon, ds_tc_args = rep_tc_args
1531                  , ds_theta = theta, ds_newtype = is_newtype
1532                  , ds_name = name, ds_cls = clas })
1533   | is_newtype
1534   = return (InstInfo { iSpec   = inst_spec
1535                      , iBinds  = NewTypeDerived co rep_tycon }, [])
1536
1537   | otherwise
1538   = do  { fix_env <- getFixityEnv
1539         ; let loc   = getSrcSpan name
1540               (meth_binds, aux_binds) = genDerivBinds loc fix_env clas rep_tycon
1541                    -- In case of a family instance, we need to use the representation
1542                    -- tycon (after all, it has the data constructors)
1543
1544         ; return (InstInfo { iSpec   = inst_spec
1545                            , iBinds  = VanillaInst meth_binds [] standalone_deriv }
1546                  , aux_binds) }
1547   where
1548     inst_spec = mkInstance oflag theta spec
1549     co1 = case tyConFamilyCoercion_maybe rep_tycon of
1550               Just co_con -> ACo (mkTyConApp co_con rep_tc_args)
1551               Nothing     -> id_co
1552               -- Not a family => rep_tycon = main tycon
1553     co2 = case newTyConCo_maybe rep_tycon of
1554               Just co_con -> ACo (mkTyConApp co_con rep_tc_args)
1555               Nothing     -> id_co  -- The newtype is transparent; no need for a cast
1556     co = co1 `mkTransCoI` co2
1557     id_co = IdCo (mkTyConApp rep_tycon rep_tc_args)
1558
1559 -- Example: newtype instance N [a] = N1 (Tree a) 
1560 --          deriving instance Eq b => Eq (N [(b,b)])
1561 -- From the instance, we get an implicit newtype R1:N a = N1 (Tree a)
1562 -- When dealing with the deriving clause
1563 --    co1 : N [(b,b)] ~ R1:N (b,b)
1564 --    co2 : R1:N (b,b) ~ Tree (b,b)
1565 --    co  : N [(b,b)] ~ Tree (b,b)
1566
1567 genDerivBinds :: SrcSpan -> FixityEnv -> Class -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1568 genDerivBinds loc fix_env clas tycon
1569   | className clas `elem` typeableClassNames
1570   = (gen_Typeable_binds loc tycon, [])
1571
1572   | otherwise
1573   = case assocMaybe gen_list (getUnique clas) of
1574         Just gen_fn -> gen_fn loc tycon
1575         Nothing     -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1576   where
1577     gen_list :: [(Unique, SrcSpan -> TyCon -> (LHsBinds RdrName, DerivAuxBinds))]
1578     gen_list = [(eqClassKey,            gen_Eq_binds)
1579                ,(ordClassKey,           gen_Ord_binds)
1580                ,(enumClassKey,          gen_Enum_binds)
1581                ,(boundedClassKey,       gen_Bounded_binds)
1582                ,(ixClassKey,            gen_Ix_binds)
1583                ,(showClassKey,          gen_Show_binds fix_env)
1584                ,(readClassKey,          gen_Read_binds fix_env)
1585                ,(dataClassKey,          gen_Data_binds)
1586                ,(functorClassKey,       gen_Functor_binds)
1587                ,(foldableClassKey,      gen_Foldable_binds)
1588                ,(traversableClassKey,   gen_Traversable_binds)
1589                ,(rep0ClassKey,          gen_Rep0_binds)
1590                ]
1591 \end{code}
1592
1593 %************************************************************************
1594 %*                                                                      *
1595 \subsection[TcDeriv-generic-binds]{Bindings for the new generic deriving mechanism}
1596 %*                                                                      *
1597 %************************************************************************
1598
1599 For the generic representation we need to generate:
1600 \begin{itemize}
1601 \item A Representable0 instance
1602 \item A Rep0 type instance 
1603 \item Many auxiliary datatypes and instances for them (for the meta-information)
1604 \end{itemize}
1605
1606 @gen_Rep0_binds@ does (1)
1607 @genGenericRepExtras@ does (2) and (3)
1608 @genGenericRepBind@ does all of them
1609
1610 \begin{code}
1611 {-
1612 genGenericRepBinds :: Bool -> [LTyClDecl Name] 
1613                    -> TcM [([(InstInfo RdrName, DerivAuxBinds)]
1614                            , MetaTyCons, TyCon)]
1615 genGenericRepBinds isBoot tyclDecls
1616   | isBoot    = return []
1617   | otherwise = do
1618       allTyDecls <- mapM tcLookupTyCon [ tcdName d | L _ d <- tyclDecls
1619                                        , isDataDecl d ]
1620       let tyDecls = filter tyConHasGenerics allTyDecls
1621       inst1 <- mapM genGenericRepBind tyDecls
1622       let (_repInsts, metaTyCons, _repTys) = unzip3 inst1
1623       metaInsts <- ASSERT (length tyDecls == length metaTyCons)
1624                      mapM genDtMeta (zip tyDecls metaTyCons)
1625       return (ASSERT (length inst1 == length metaInsts)
1626                 [ (ri : mi, ms, rt) 
1627                 | ((ri, ms, rt), mi) <- zip inst1 metaInsts ])
1628 -}
1629
1630 gen_Rep0_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1631 gen_Rep0_binds _ tc = (mkBindsRep0 tc, [ {- No DerivAuxBinds -} ])
1632
1633 genGenericRepExtras :: TyCon -> TcM (MetaTyCons, TyCon)
1634 genGenericRepExtras tc =
1635   do  uniqS <- newUniqueSupply
1636       let
1637         -- Uniques for everyone
1638         (uniqD:uniqs) = uniqsFromSupply uniqS
1639         (uniqsC,us) = splitAt (length tc_cons) uniqs
1640         uniqsS :: [[Unique]] -- Unique supply for the S datatypes
1641         uniqsS = mkUniqsS tc_arits us
1642         mkUniqsS []    _  = []
1643         mkUniqsS (n:t) us = case splitAt n us of
1644                               (us1,us2) -> us1 : mkUniqsS t us2
1645
1646         tc_name   = tyConName tc
1647         tc_cons   = tyConDataCons tc
1648         tc_arits  = map dataConSourceArity tc_cons
1649         
1650         tc_occ    = nameOccName tc_name
1651         d_occ     = mkGenD tc_occ
1652         c_occ m   = mkGenC tc_occ m
1653         s_occ m n = mkGenS tc_occ m n
1654         mod_name  = nameModule (tyConName tc)
1655         d_name    = mkExternalName uniqD mod_name d_occ wiredInSrcSpan
1656         c_names   = [ mkExternalName u mod_name (c_occ m) wiredInSrcSpan
1657                       | (u,m) <- zip uniqsC [0..] ]
1658         s_names   = [ [ mkExternalName u mod_name (s_occ m n) wiredInSrcSpan 
1659                         | (u,n) <- zip us [0..] ] | (us,m) <- zip uniqsS [0..] ]
1660         
1661         mkTyCon name = ASSERT( isExternalName name )
1662                          buildAlgTyCon name [] [] mkAbstractTyConRhs
1663                            NonRecursive False NoParentTyCon Nothing
1664
1665       metaDTyCon  <- mkTyCon d_name
1666       metaCTyCons <- sequence [ mkTyCon c_name | c_name <- c_names ]
1667       metaSTyCons <- mapM sequence 
1668                        [ [ mkTyCon s_name 
1669                          | s_name <- s_namesC ] | s_namesC <- s_names ]
1670
1671       let metaDts = MetaTyCons metaDTyCon metaCTyCons metaSTyCons
1672   
1673       rep0_tycon <- tc_mkRep0TyCon tc metaDts
1674
1675       return (metaDts, rep0_tycon)
1676 {-
1677 genGenericRepBind :: TyCon
1678                   -> TcM ((InstInfo RdrName, DerivAuxBinds), MetaTyCons, TyCon)
1679 genGenericRepBind tc =
1680   do  (metaDts, rep0_tycon)     <- genGenericRepExtras tc
1681       clas                      <- tcLookupClass rep0ClassName
1682       dfun_name                 <- new_dfun_name clas tc
1683       let
1684         mkInstRep0 = (InstInfo { iSpec = inst, iBinds = binds }
1685                                , [ {- No DerivAuxBinds -} ])
1686         inst  = mkLocalInstance dfun NoOverlap
1687         binds = VanillaInst (mkBindsRep0 tc) [] False
1688
1689         tvs   = tyConTyVars tc
1690         tc_ty = mkTyConApp tc (mkTyVarTys tvs)
1691         
1692         dfun  = mkDictFunId dfun_name (tyConTyVars tc) [] clas [tc_ty]
1693       return (mkInstRep0, metaDts, rep0_tycon)
1694 -}
1695 genDtMeta :: (TyCon, MetaTyCons) -> TcM [(InstInfo RdrName, DerivAuxBinds)]
1696 genDtMeta (tc,metaDts) =
1697   do  dClas <- tcLookupClass datatypeClassName
1698       d_dfun_name <- new_dfun_name dClas tc
1699       cClas <- tcLookupClass constructorClassName
1700       c_dfun_names <- sequence [ new_dfun_name cClas tc | _ <- metaC metaDts ]
1701       sClas <- tcLookupClass selectorClassName
1702       s_dfun_names <- sequence (map sequence [ [ new_dfun_name sClas tc 
1703                                                | _ <- x ] 
1704                                              | x <- metaS metaDts ])
1705       fix_env <- getFixityEnv
1706
1707       let
1708         (dBinds,cBinds,sBinds) = mkBindsMetaD fix_env tc
1709         
1710         -- Datatype
1711         d_metaTycon = metaD metaDts
1712         d_inst = mkLocalInstance d_dfun NoOverlap
1713         d_binds = VanillaInst dBinds [] False
1714         d_dfun  = mkDictFunId d_dfun_name (tyConTyVars tc) [] dClas 
1715                     [ mkTyConTy d_metaTycon ]
1716         d_mkInst = (InstInfo { iSpec = d_inst, iBinds = d_binds }, [])
1717         
1718         -- Constructor
1719         c_metaTycons = metaC metaDts
1720         c_insts = [ mkLocalInstance (c_dfun c ds) NoOverlap 
1721                   | (c, ds) <- myZip1 c_metaTycons c_dfun_names ]
1722         c_binds = [ VanillaInst c [] False | c <- cBinds ]
1723         c_dfun c dfun_name = mkDictFunId dfun_name (tyConTyVars tc) [] cClas 
1724                                [ mkTyConTy c ]
1725         c_mkInst = [ (InstInfo { iSpec = is, iBinds = bs }, []) 
1726                    | (is,bs) <- myZip1 c_insts c_binds ]
1727         
1728         -- Selector
1729         s_metaTycons = metaS metaDts
1730         s_insts = map (map (\(s,ds) -> mkLocalInstance (s_dfun s ds) NoOverlap))
1731                     (myZip2 s_metaTycons s_dfun_names)
1732         s_binds = [ [ VanillaInst s [] False | s <- ss ] | ss <- sBinds ]
1733         s_dfun s dfun_name = mkDictFunId dfun_name (tyConTyVars tc) [] sClas
1734                                [ mkTyConTy s ]
1735         s_mkInst = map (map (\(is,bs) -> (InstInfo {iSpec=is, iBinds=bs}, [])))
1736                      (myZip2 s_insts s_binds)
1737        
1738         myZip1 :: [a] -> [b] -> [(a,b)]
1739         myZip1 l1 l2 = ASSERT (length l1 == length l2) zip l1 l2
1740         
1741         myZip2 :: [[a]] -> [[b]] -> [[(a,b)]]
1742         myZip2 l1 l2 =
1743           ASSERT (and (zipWith (>=) (map length l1) (map length l2)))
1744             [ zip x1 x2 | (x1,x2) <- zip l1 l2 ]
1745         
1746       return (d_mkInst : c_mkInst ++ concat s_mkInst)
1747 \end{code}
1748
1749
1750 %************************************************************************
1751 %*                                                                      *
1752 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1753 %*                                                                      *
1754 %************************************************************************
1755
1756 \begin{code}
1757 derivingKindErr :: TyCon -> Class -> [Type] -> Kind -> Message
1758 derivingKindErr tc cls cls_tys cls_kind
1759   = hang (ptext (sLit "Cannot derive well-kinded instance of form")
1760                 <+> quotes (pprClassPred cls cls_tys <+> parens (ppr tc <+> ptext (sLit "..."))))
1761        2 (ptext (sLit "Class") <+> quotes (ppr cls)
1762             <+> ptext (sLit "expects an argument of kind") <+> quotes (pprKind cls_kind))
1763
1764 derivingEtaErr :: Class -> [Type] -> Type -> Message
1765 derivingEtaErr cls cls_tys inst_ty
1766   = sep [ptext (sLit "Cannot eta-reduce to an instance of form"),
1767          nest 2 (ptext (sLit "instance (...) =>")
1768                 <+> pprClassPred cls (cls_tys ++ [inst_ty]))]
1769
1770 typeFamilyPapErr :: TyCon -> Class -> [Type] -> Type -> Message
1771 typeFamilyPapErr tc cls cls_tys inst_ty
1772   = hang (ptext (sLit "Derived instance") <+> quotes (pprClassPred cls (cls_tys ++ [inst_ty])))
1773        2 (ptext (sLit "requires illegal partial application of data type family") <+> ppr tc) 
1774
1775 derivingThingErr :: Bool -> Class -> [Type] -> Type -> Message -> Message
1776 derivingThingErr newtype_deriving clas tys ty why
1777   = sep [(hang (ptext (sLit "Can't make a derived instance of"))
1778              2 (quotes (ppr pred)) 
1779           $$ nest 2 extra) <> colon,
1780          nest 2 why]
1781   where
1782     extra | newtype_deriving = ptext (sLit "(even with cunning newtype deriving)")
1783           | otherwise        = empty
1784     pred = mkClassPred clas (tys ++ [ty])
1785
1786 derivingHiddenErr :: TyCon -> SDoc
1787 derivingHiddenErr tc
1788   = hang (ptext (sLit "The data constructors of") <+> quotes (ppr tc) <+> ptext (sLit "are not all in scope"))
1789        2 (ptext (sLit "so you cannot derive an instance for it"))
1790
1791 standaloneCtxt :: LHsType Name -> SDoc
1792 standaloneCtxt ty = hang (ptext (sLit "In the stand-alone deriving instance for")) 
1793                        2 (quotes (ppr ty))
1794
1795 derivInstCtxt :: PredType -> Message
1796 derivInstCtxt pred
1797   = ptext (sLit "When deriving the instance for") <+> parens (ppr pred)
1798
1799 badDerivedPred :: PredType -> Message
1800 badDerivedPred pred
1801   = vcat [ptext (sLit "Can't derive instances where the instance context mentions"),
1802           ptext (sLit "type variables that are not data type parameters"),
1803           nest 2 (ptext (sLit "Offending constraint:") <+> ppr pred)]
1804 \end{code}