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