Fix Trac #2856: make deriving work for type families
[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 Var
44 import VarSet
45 import PrelNames
46 import SrcLoc
47 import Util
48 import ListSetOps
49 import Outputable
50 import FastString
51 import Bag
52 \end{code}
53
54 %************************************************************************
55 %*                                                                      *
56                 Overview
57 %*                                                                      *
58 %************************************************************************
59
60 Overall plan
61 ~~~~~~~~~~~~
62 1.  Convert the decls (i.e. data/newtype deriving clauses, 
63     plus standalone deriving) to [EarlyDerivSpec]
64
65 2.  Infer the missing contexts for the Left DerivSpecs
66
67 3.  Add the derived bindings, generating InstInfos
68
69 \begin{code}
70 -- DerivSpec is purely  local to this module
71 data DerivSpec  = DS { ds_loc     :: SrcSpan 
72                      , ds_orig    :: InstOrigin 
73                      , ds_name    :: Name
74                      , ds_tvs     :: [TyVar] 
75                      , ds_theta   :: ThetaType
76                      , ds_cls     :: Class
77                      , ds_tys     :: [Type]
78                      , ds_tc      :: TyCon
79                      , ds_tc_args :: [Type]
80                      , ds_newtype :: Bool }
81         -- This spec implies a dfun declaration of the form
82         --       df :: forall tvs. theta => C tys
83         -- The Name is the name for the DFun we'll build
84         -- The tyvars bind all the variables in the theta
85         -- For family indexes, the tycon in 
86         --       in ds_tys is the *family* tycon
87         --       in ds_tc, ds_tc_args is the *representation* tycon
88         -- For non-family tycons, both are the same
89
90         -- ds_newtype = True  <=> Newtype deriving
91         --              False <=> Vanilla deriving
92
93 type EarlyDerivSpec = Either DerivSpec DerivSpec
94         -- Left  ds => the context for the instance should be inferred
95         --             In this case ds_theta is the list of all the 
96         --                constraints needed, such as (Eq [a], Eq a)
97         --                The inference process is to reduce this to a 
98         --                simpler form (e.g. Eq a)
99         -- 
100         -- Right ds => the exact context for the instance is supplied 
101         --             by the programmer; it is ds_theta
102
103 pprDerivSpec :: DerivSpec -> SDoc
104 pprDerivSpec (DS { ds_loc = l, ds_name = n, ds_tvs = tvs, 
105                    ds_cls = c, ds_tys = tys, ds_theta = rhs })
106   = parens (hsep [ppr l, ppr n, ppr tvs, ppr c, ppr tys]
107             <+> equals <+> ppr rhs)
108 \end{code}
109
110
111 Inferring missing contexts 
112 ~~~~~~~~~~~~~~~~~~~~~~~~~~
113 Consider
114
115         data T a b = C1 (Foo a) (Bar b)
116                    | C2 Int (T b a)
117                    | C3 (T a a)
118                    deriving (Eq)
119
120 [NOTE: See end of these comments for what to do with 
121         data (C a, D b) => T a b = ...
122 ]
123
124 We want to come up with an instance declaration of the form
125
126         instance (Ping a, Pong b, ...) => Eq (T a b) where
127                 x == y = ...
128
129 It is pretty easy, albeit tedious, to fill in the code "...".  The
130 trick is to figure out what the context for the instance decl is,
131 namely @Ping@, @Pong@ and friends.
132
133 Let's call the context reqd for the T instance of class C at types
134 (a,b, ...)  C (T a b).  Thus:
135
136         Eq (T a b) = (Ping a, Pong b, ...)
137
138 Now we can get a (recursive) equation from the @data@ decl:
139
140         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
141                    u Eq (T b a) u Eq Int        -- From C2
142                    u Eq (T a a)                 -- From C3
143
144 Foo and Bar may have explicit instances for @Eq@, in which case we can
145 just substitute for them.  Alternatively, either or both may have
146 their @Eq@ instances given by @deriving@ clauses, in which case they
147 form part of the system of equations.
148
149 Now all we need do is simplify and solve the equations, iterating to
150 find the least fixpoint.  Notice that the order of the arguments can
151 switch around, as here in the recursive calls to T.
152
153 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
154
155 We start with:
156
157         Eq (T a b) = {}         -- The empty set
158
159 Next iteration:
160         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
161                    u Eq (T b a) u Eq Int        -- From C2
162                    u Eq (T a a)                 -- From C3
163
164         After simplification:
165                    = Eq a u Ping b u {} u {} u {}
166                    = Eq a u Ping b
167
168 Next iteration:
169
170         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
171                    u Eq (T b a) u Eq Int        -- From C2
172                    u Eq (T a a)                 -- From C3
173
174         After simplification:
175                    = Eq a u Ping b
176                    u (Eq b u Ping a)
177                    u (Eq a u Ping a)
178
179                    = Eq a u Ping b u Eq b u Ping a
180
181 The next iteration gives the same result, so this is the fixpoint.  We
182 need to make a canonical form of the RHS to ensure convergence.  We do
183 this by simplifying the RHS to a form in which
184
185         - the classes constrain only tyvars
186         - the list is sorted by tyvar (major key) and then class (minor key)
187         - no duplicates, of course
188
189 So, here are the synonyms for the ``equation'' structures:
190
191
192 Note [Data decl contexts]
193 ~~~~~~~~~~~~~~~~~~~~~~~~~
194 Consider
195
196         data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
197
198 We will need an instance decl like:
199
200         instance (Read a, RealFloat a) => Read (Complex a) where
201           ...
202
203 The RealFloat in the context is because the read method for Complex is bound
204 to construct a Complex, and doing that requires that the argument type is
205 in RealFloat. 
206
207 But this ain't true for Show, Eq, Ord, etc, since they don't construct
208 a Complex; they only take them apart.
209
210 Our approach: identify the offending classes, and add the data type
211 context to the instance decl.  The "offending classes" are
212
213         Read, Enum?
214
215 FURTHER NOTE ADDED March 2002.  In fact, Haskell98 now requires that
216 pattern matching against a constructor from a data type with a context
217 gives rise to the constraints for that context -- or at least the thinned
218 version.  So now all classes are "offending".
219
220 Note [Newtype deriving]
221 ~~~~~~~~~~~~~~~~~~~~~~~
222 Consider this:
223     class C a b
224     instance C [a] Char
225     newtype T = T Char deriving( C [a] )
226
227 Notice the free 'a' in the deriving.  We have to fill this out to 
228     newtype T = T Char deriving( forall a. C [a] )
229
230 And then translate it to:
231     instance C [a] Char => C [a] T where ...
232     
233         
234 Note [Newtype deriving superclasses]
235 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
236 (See also Trac #1220 for an interesting exchange on newtype
237 deriving and superclasses.)
238
239 The 'tys' here come from the partial application in the deriving
240 clause. The last arg is the new instance type.
241
242 We must pass the superclasses; the newtype might be an instance
243 of them in a different way than the representation type
244 E.g.            newtype Foo a = Foo a deriving( Show, Num, Eq )
245 Then the Show instance is not done via isomorphism; it shows
246         Foo 3 as "Foo 3"
247 The Num instance is derived via isomorphism, but the Show superclass
248 dictionary must the Show instance for Foo, *not* the Show dictionary
249 gotten from the Num dictionary. So we must build a whole new dictionary
250 not just use the Num one.  The instance we want is something like:
251      instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
252         (+) = ((+)@a)
253         ...etc...
254 There may be a coercion needed which we get from the tycon for the newtype
255 when the dict is constructed in TcInstDcls.tcInstDecl2
256
257
258
259
260 %************************************************************************
261 %*                                                                      *
262 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
263 %*                                                                      *
264 %************************************************************************
265
266 \begin{code}
267 tcDeriving  :: [LTyClDecl Name]  -- All type constructors
268             -> [LInstDecl Name]  -- All instance declarations
269             -> [LDerivDecl Name] -- All stand-alone deriving declarations
270             -> TcM ([InstInfo Name],    -- The generated "instance decls"
271                     HsValBinds Name)    -- Extra generated top-level bindings
272
273 tcDeriving tycl_decls inst_decls deriv_decls
274   = recoverM (return ([], emptyValBindsOut)) $
275     do  {       -- Fish the "deriving"-related information out of the TcEnv
276                 -- And make the necessary "equations".
277           is_boot <- tcIsHsBoot
278         ; traceTc (text "tcDeriving" <+> ppr is_boot)
279         ; early_specs <- makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
280
281         ; overlap_flag <- getOverlapFlag
282         ; let (infer_specs, given_specs) = splitEithers early_specs
283         ; insts1 <- mapM (genInst overlap_flag) given_specs
284
285         ; final_specs <- extendLocalInstEnv (map (iSpec . fst) insts1) $
286                          inferInstanceContexts overlap_flag infer_specs
287
288         ; insts2 <- mapM (genInst overlap_flag) final_specs
289
290                  -- Generate the generic to/from functions from each type declaration
291         ; gen_binds <- mkGenericBinds is_boot
292         ; (inst_info, rn_binds) <- renameDeriv is_boot gen_binds (insts1 ++ insts2)
293
294         ; dflags <- getDOpts
295         ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
296                  (ddump_deriving inst_info rn_binds))
297
298         ; return (inst_info, rn_binds) }
299   where
300     ddump_deriving :: [InstInfo Name] -> HsValBinds Name -> SDoc
301     ddump_deriving inst_infos extra_binds
302       = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
303
304 renameDeriv :: Bool -> LHsBinds RdrName
305             -> [(InstInfo RdrName, DerivAuxBinds)]
306             -> TcM ([InstInfo Name], HsValBinds Name)
307 renameDeriv is_boot gen_binds insts
308   | is_boot     -- If we are compiling a hs-boot file, don't generate any derived bindings
309                 -- The inst-info bindings will all be empty, but it's easier to
310                 -- just use rn_inst_info to change the type appropriately
311   = do  { rn_inst_infos <- mapM rn_inst_info inst_infos 
312         ; return (rn_inst_infos, emptyValBindsOut) }
313
314   | otherwise
315   = discardWarnings $    -- Discard warnings about unused bindings etc
316     do  { (rn_gen, dus_gen) <- setOptM Opt_ScopedTypeVariables $  -- Type signatures in patterns 
317                                                                   -- are used in the generic binds
318                                rnTopBinds (ValBindsIn gen_binds [])
319         ; keepAliveSetTc (duDefs dus_gen)       -- Mark these guys to be kept alive
320
321                 -- Generate and rename any extra not-one-inst-decl-specific binds, 
322                 -- notably "con2tag" and/or "tag2con" functions.  
323                 -- Bring those names into scope before renaming the instances themselves
324         ; loc <- getSrcSpanM    -- Generic loc for shared bindings
325         ; let aux_binds = listToBag $ map (genAuxBind loc) $ 
326                           rm_dups [] $ concat deriv_aux_binds
327         ; rn_aux_lhs <- rnTopBindsLHS emptyFsEnv (ValBindsIn aux_binds [])
328         ; let aux_names = map unLoc (collectHsValBinders rn_aux_lhs)
329
330         ; bindLocalNames aux_names $ 
331     do  { (rn_aux, _dus) <- rnTopBindsRHS (mkNameSet aux_names) rn_aux_lhs
332         ; rn_inst_infos <- mapM rn_inst_info inst_infos
333         ; return (rn_inst_infos, rn_aux `plusHsValBinds` rn_gen) } }
334
335   where
336     (inst_infos, deriv_aux_binds) = unzip insts
337     
338         -- Remove duplicate requests for auxilliary bindings
339     rm_dups acc [] = acc
340     rm_dups acc (b:bs) | any (isDupAux b) acc = rm_dups acc bs
341                        | otherwise            = rm_dups (b:acc) bs
342
343
344     rn_inst_info (InstInfo { iSpec = inst, iBinds = NewTypeDerived co })
345         = return (InstInfo { iSpec = inst, iBinds = NewTypeDerived co })
346
347     rn_inst_info (InstInfo { iSpec = inst, iBinds = VanillaInst binds sigs })
348         =       -- Bring the right type variables into 
349                 -- scope (yuk), and rename the method binds
350            ASSERT( null sigs )
351            bindLocalNames (map Var.varName tyvars) $
352            do { (rn_binds, _fvs) <- rnMethodBinds clas_nm (\_ -> []) [] binds
353               ; return (InstInfo { iSpec = inst, iBinds = VanillaInst rn_binds [] }) }
354         where
355           (tyvars,_,clas,_) = instanceHead inst
356           clas_nm           = className clas
357
358 -----------------------------------------
359 mkGenericBinds :: Bool -> TcM (LHsBinds RdrName)
360 mkGenericBinds is_boot
361   | is_boot 
362   = return emptyBag
363   | otherwise
364   = do  { gbl_env <- getGblEnv
365         ; let tcs = typeEnvTyCons (tcg_type_env gbl_env)
366         ; return (unionManyBags [ mkTyConGenericBinds tc | 
367                                   tc <- tcs, tyConHasGenerics tc ]) }
368                 -- We are only interested in the data type declarations,
369                 -- and then only in the ones whose 'has-generics' flag is on
370                 -- The predicate tyConHasGenerics finds both of these
371 \end{code}
372
373
374 %************************************************************************
375 %*                                                                      *
376                 From HsSyn to DerivSpec
377 %*                                                                      *
378 %************************************************************************
379
380 @makeDerivSpecs@ fishes around to find the info about needed derived instances.
381
382 \begin{code}
383 makeDerivSpecs :: Bool 
384                -> [LTyClDecl Name] 
385                -> [LInstDecl Name]
386                -> [LDerivDecl Name] 
387                -> TcM [EarlyDerivSpec]
388
389 makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
390   | is_boot     -- No 'deriving' at all in hs-boot files
391   = do  { mapM_ add_deriv_err deriv_locs 
392         ; return [] }
393   | otherwise
394   = do  { eqns1 <- mapAndRecoverM deriveTyData all_tydata
395         ; eqns2 <- mapAndRecoverM deriveStandalone deriv_decls
396         ; return (eqns1 ++ eqns2) }
397   where
398     extractTyDataPreds decls
399       = [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
400
401     all_tydata :: [(LHsType Name, LTyClDecl Name)]
402         -- Derived predicate paired with its data type declaration
403     all_tydata = extractTyDataPreds tycl_decls ++
404                  [ pd                -- Traverse assoc data families
405                  | L _ (InstDecl _ _ _ ats) <- inst_decls
406                  , pd <- extractTyDataPreds ats ]
407
408     deriv_locs = map (getLoc . snd) all_tydata
409                  ++ map getLoc deriv_decls
410
411     add_deriv_err loc = setSrcSpan loc $
412                         addErr (hang (ptext (sLit "Deriving not permitted in hs-boot file"))
413                                    2 (ptext (sLit "Use an instance declaration instead")))
414
415 ------------------------------------------------------------------
416 deriveStandalone :: LDerivDecl Name -> TcM EarlyDerivSpec
417 -- Standalone deriving declarations
418 --  e.g.   deriving instance Show a => Show (T a)
419 -- Rather like tcLocalInstDecl
420 deriveStandalone (L loc (DerivDecl deriv_ty))
421   = setSrcSpan loc                   $
422     addErrCtxt (standaloneCtxt deriv_ty)  $
423     do { traceTc (text "standalone deriving decl for" <+> ppr deriv_ty)
424        ; (tvs, theta, tau) <- tcHsInstHead deriv_ty
425        ; traceTc (text "standalone deriving;"
426               <+> text "tvs:" <+> ppr tvs
427               <+> text "theta:" <+> ppr theta
428               <+> text "tau:" <+> ppr tau)
429        ; (cls, inst_tys) <- checkValidInstHead tau
430        ; checkValidInstance tvs theta cls inst_tys
431                 -- C.f. TcInstDcls.tcLocalInstDecl1
432
433        ; let cls_tys = take (length inst_tys - 1) inst_tys
434              inst_ty = last inst_tys
435        ; traceTc (text "standalone deriving;"
436               <+> text "class:" <+> ppr cls
437               <+> text "class types:" <+> ppr cls_tys
438               <+> text "type:" <+> ppr inst_ty)
439        ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
440                    (Just theta) }
441
442 ------------------------------------------------------------------
443 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM EarlyDerivSpec
444 deriveTyData (L loc deriv_pred, L _ decl@(TyData { tcdLName = L _ tycon_name, 
445                                                    tcdTyVars = tv_names, 
446                                                    tcdTyPats = ty_pats }))
447   = setSrcSpan loc     $        -- Use the location of the 'deriving' item
448     tcAddDeclCtxt decl $
449     do  { (tvs, tc, tc_args) <- get_lhs ty_pats
450         ; tcExtendTyVarEnv tvs $        -- Deriving preds may (now) mention
451                                         -- the type variables for the type constructor
452
453     do  { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
454                 -- The "deriv_pred" is a LHsType to take account of the fact that for
455                 -- newtype deriving we allow deriving (forall a. C [a]).
456
457         -- Given data T a b c = ... deriving( C d ),
458         -- we want to drop type variables from T so that (C d (T a)) is well-kinded
459         ; let cls_tyvars = classTyVars cls
460               kind = tyVarKind (last cls_tyvars)
461               (arg_kinds, _) = splitKindFunTys kind
462               n_args_to_drop = length arg_kinds 
463               n_args_to_keep = tyConArity tc - n_args_to_drop
464               args_to_drop   = drop n_args_to_keep tc_args
465               inst_ty        = mkTyConApp tc (take n_args_to_keep tc_args)
466               inst_ty_kind   = typeKind inst_ty
467               dropped_tvs    = mkVarSet (mapCatMaybes getTyVar_maybe args_to_drop)
468               univ_tvs       = (mkVarSet tvs `extendVarSetList` deriv_tvs)
469                                         `minusVarSet` dropped_tvs
470  
471         -- Check that the result really is well-kinded
472         ; checkTc (n_args_to_keep >= 0 && (inst_ty_kind `eqKind` kind))
473                   (derivingKindErr tc cls cls_tys kind)
474
475         ; checkTc (sizeVarSet dropped_tvs == n_args_to_drop &&           -- (a)
476                    tyVarsOfTypes (inst_ty:cls_tys) `subVarSet` univ_tvs) -- (b)
477                   (derivingEtaErr cls cls_tys inst_ty)
478                 -- Check that 
479                 --  (a) The data type can be eta-reduced; eg reject:
480                 --              data instance T a a = ... deriving( Monad )
481                 --  (b) The type class args do not mention any of the dropped type
482                 --      variables 
483                 --              newtype T a s = ... deriving( ST s )
484
485         -- Type families can't be partially applied
486         -- e.g.   newtype instance T Int a = MkT [a] deriving( Monad )
487         -- Note [Deriving, type families, and partial applications]
488         ; checkTc (not (isOpenTyCon tc) || n_args_to_drop == 0)
489                   (typeFamilyPapErr tc cls cls_tys inst_ty)
490
491         ; mkEqnHelp DerivOrigin (varSetElems univ_tvs) cls cls_tys inst_ty Nothing } }
492   where
493         -- Tiresomely we must figure out the "lhs", which is awkward for type families
494         -- E.g.   data T a b = .. deriving( Eq )
495         --          Here, the lhs is (T a b)
496         --        data instance TF Int b = ... deriving( Eq )
497         --          Here, the lhs is (TF Int b)
498         -- But if we just look up the tycon_name, we get is the *family*
499         -- tycon, but not pattern types -- they are in the *rep* tycon.
500     get_lhs Nothing     = do { tc <- tcLookupTyCon tycon_name
501                              ; let tvs = tyConTyVars tc
502                              ; return (tvs, tc, mkTyVarTys tvs) }
503     get_lhs (Just pats) = do { let hs_app = nlHsTyConApp tycon_name pats
504                              ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
505                              ; let (tc, tc_args) = tcSplitTyConApp tc_app
506                              ; return (tvs, tc, tc_args) }
507
508 deriveTyData _other
509   = panic "derivTyData" -- Caller ensures that only TyData can happen
510 \end{code}
511
512 Note [Deriving, type families, and partial applications]
513 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
514 When there are no type families, it's quite easy:
515
516     newtype S a = MkS [a]
517     -- :CoS :: S  ~ []  -- Eta-reduced
518
519     instance Eq [a] => Eq (S a)         -- by coercion sym (Eq (coMkS a)) : Eq [a] ~ Eq (S a)
520     instance Monad [] => Monad S        -- by coercion sym (Monad coMkS)  : Monad [] ~ Monad S 
521
522 When type familes are involved it's trickier:
523
524     data family T a b
525     newtype instance T Int a = MkT [a] deriving( Eq, Monad )
526     -- :RT is the representation type for (T Int a)
527     --  :CoF:R1T a :: T Int a ~ :RT a   -- Not eta reduced
528     --  :Co:R1T    :: :RT ~ []          -- Eta-reduced
529
530     instance Eq [a] => Eq (T Int a)     -- easy by coercion
531     instance Monad [] => Monad (T Int)  -- only if we can eta reduce???
532
533 The "???" bit is that we don't build the :CoF thing in eta-reduced form
534 Henc the current typeFamilyPapErr, even though the instance makes sense.
535 After all, we can write it out
536     instance Monad [] => Monad (T Int)  -- only if we can eta reduce???
537       return x = MkT [x]
538       ... etc ...       
539
540 \begin{code}
541 mkEqnHelp :: InstOrigin -> [TyVar] -> Class -> [Type] -> Type
542           -> Maybe ThetaType    -- Just    => context supplied (standalone deriving)
543                                 -- Nothing => context inferred (deriving on data decl)
544           -> TcRn EarlyDerivSpec
545 -- Make the EarlyDerivSpec for an instance
546 --      forall tvs. theta => cls (tys ++ [ty])
547 -- where the 'theta' is optional (that's the Maybe part)
548 -- Assumes that this declaration is well-kinded
549
550 mkEqnHelp orig tvs cls cls_tys tc_app mtheta
551   | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
552   , isAlgTyCon tycon    -- Check for functions, primitive types etc
553   = do  { (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon tc_args
554                   -- Be careful to test rep_tc here: in the case of families, 
555                   -- we want to check the instance tycon, not the family tycon
556
557         -- For standalone deriving (mtheta /= Nothing), 
558         -- check that all the data constructors are in scope.
559         -- No need for this when deriving Typeable, becuase we don't need
560         -- the constructors for that.
561         ; rdr_env <- getGlobalRdrEnv
562         ; let hidden_data_cons = isAbstractTyCon rep_tc || any not_in_scope (tyConDataCons rep_tc)
563               not_in_scope dc  = null (lookupGRE_Name rdr_env (dataConName dc))
564         ; checkTc (isNothing mtheta || 
565                    not hidden_data_cons ||
566                    className cls `elem` typeableClassNames) 
567                   (derivingHiddenErr tycon)
568
569         ; mayDeriveDataTypeable <- doptM Opt_DeriveDataTypeable
570         ; newtype_deriving <- doptM Opt_GeneralizedNewtypeDeriving
571
572         ; if isDataTyCon rep_tc then
573                 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys 
574                               tycon tc_args rep_tc rep_tc_args mtheta
575           else
576                 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving
577                              tvs cls cls_tys 
578                              tycon tc_args rep_tc rep_tc_args mtheta }
579   | otherwise
580   = failWithTc (derivingThingErr cls cls_tys tc_app
581                (ptext (sLit "The last argument of the instance must be a data or newtype application")))
582 \end{code}
583
584 Note [Looking up family instances for deriving]
585 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
586 tcLookupFamInstExact is an auxiliary lookup wrapper which requires
587 that looked-up family instances exist.  If called with a vanilla
588 tycon, the old type application is simply returned.
589
590 If we have
591   data instance F () = ... deriving Eq
592   data instance F () = ... deriving Eq
593 then tcLookupFamInstExact will be confused by the two matches;
594 but that can't happen because tcInstDecls1 doesn't call tcDeriving
595 if there are any overlaps.
596
597 There are two other things that might go wrong with the lookup.
598 First, we might see a standalone deriving clause
599         deriving Eq (F ())
600 when there is no data instance F () in scope. 
601
602 Note that it's OK to have
603   data instance F [a] = ...
604   deriving Eq (F [(a,b)])
605 where the match is not exact; the same holds for ordinary data types
606 with standalone deriving declrations.
607
608 \begin{code}
609 tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
610 tcLookupFamInstExact tycon tys
611   | not (isOpenTyCon tycon)
612   = return (tycon, tys)
613   | otherwise
614   = do { maybeFamInst <- tcLookupFamInst tycon tys
615        ; case maybeFamInst of
616            Nothing      -> famInstNotFound tycon tys
617            Just famInst -> return famInst
618        }
619
620 famInstNotFound :: TyCon -> [Type] -> TcM a
621 famInstNotFound tycon tys 
622   = failWithTc (ptext (sLit "No family instance for")
623                         <+> quotes (pprTypeApp tycon tys))
624 \end{code}
625
626
627 %************************************************************************
628 %*                                                                      *
629                 Deriving data types
630 %*                                                                      *
631 %************************************************************************
632
633 \begin{code}
634 mkDataTypeEqn :: InstOrigin -> Bool -> [Var] -> Class -> [Type]
635               -> TyCon -> [Type] -> TyCon -> [Type] -> Maybe ThetaType
636               -> TcRn EarlyDerivSpec    -- Return 'Nothing' if error
637                 
638 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
639               tycon tc_args rep_tc rep_tc_args mtheta
640   = case checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc of
641         -- NB: pass the *representation* tycon to checkSideConditions
642         CanDerive -> mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
643         NonDerivableClass       -> bale_out (nonStdErr cls)
644         DerivableClassError msg -> bale_out msg
645   where
646     bale_out msg = failWithTc (derivingThingErr cls cls_tys (mkTyConApp tycon tc_args) msg)
647
648 mk_data_eqn, mk_typeable_eqn
649    :: InstOrigin -> [TyVar] -> Class 
650    -> TyCon -> [TcType] -> TyCon -> [TcType] -> Maybe ThetaType
651    -> TcM EarlyDerivSpec
652 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
653   | getName cls `elem` typeableClassNames
654   = mk_typeable_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
655
656   | otherwise
657   = do  { dfun_name <- new_dfun_name cls tycon
658         ; loc <- getSrcSpanM
659         ; let ordinary_constraints
660                 = [ mkClassPred cls [arg_ty] 
661                   | data_con <- tyConDataCons rep_tc,
662                     arg_ty   <- ASSERT( isVanillaDataCon data_con )
663                                 dataConInstOrigArgTys data_con rep_tc_args,
664                     not (isUnLiftedType arg_ty) ]
665                         -- No constraints for unlifted types
666                         -- Where they are legal we generate specilised function calls
667
668                         -- See Note [Superclasses of derived instance]
669               sc_constraints = substTheta (zipOpenTvSubst (classTyVars cls) inst_tys)
670                                           (classSCTheta cls)
671               inst_tys = [mkTyConApp tycon tc_args]
672
673               stupid_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
674               stupid_constraints = substTheta stupid_subst (tyConStupidTheta rep_tc)
675               all_constraints = stupid_constraints ++ sc_constraints ++ ordinary_constraints
676
677               spec = DS { ds_loc = loc, ds_orig = orig
678                         , ds_name = dfun_name, ds_tvs = tvs 
679                         , ds_cls = cls, ds_tys = inst_tys
680                         , ds_tc = rep_tc, ds_tc_args = rep_tc_args
681                         , ds_theta =  mtheta `orElse` all_constraints
682                         , ds_newtype = False }
683
684         ; return (if isJust mtheta then Right spec      -- Specified context
685                                    else Left spec) }    -- Infer context
686
687 mk_typeable_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
688         -- The Typeable class is special in several ways
689         --        data T a b = ... deriving( Typeable )
690         -- gives
691         --        instance Typeable2 T where ...
692         -- Notice that:
693         -- 1. There are no constraints in the instance
694         -- 2. There are no type variables either
695         -- 3. The actual class we want to generate isn't necessarily
696         --      Typeable; it depends on the arity of the type
697   | isNothing mtheta    -- deriving on a data type decl
698   = do  { checkTc (cls `hasKey` typeableClassKey)
699                   (ptext (sLit "Use deriving( Typeable ) on a data type declaration"))
700         ; real_cls <- tcLookupClass (typeableClassNames !! tyConArity tycon)
701         ; mk_typeable_eqn orig tvs real_cls tycon [] rep_tc [] (Just []) }
702
703   | otherwise           -- standaone deriving
704   = do  { checkTc (null tc_args)
705                   (ptext (sLit "Derived typeable instance must be of form (Typeable") 
706                         <> int (tyConArity tycon) <+> ppr tycon <> rparen)
707         ; dfun_name <- new_dfun_name cls tycon
708         ; loc <- getSrcSpanM
709         ; return (Right $
710                   DS { ds_loc = loc, ds_orig = orig, ds_name = dfun_name, ds_tvs = []
711                      , ds_cls = cls, ds_tys = [mkTyConApp tycon []]
712                      , ds_tc = rep_tc, ds_tc_args = rep_tc_args
713                      , ds_theta = mtheta `orElse` [], ds_newtype = False })  }
714
715 ------------------------------------------------------------------
716 -- Check side conditions that dis-allow derivability for particular classes
717 -- This is *apart* from the newtype-deriving mechanism
718 --
719 -- Here we get the representation tycon in case of family instances as it has
720 -- the data constructors - but we need to be careful to fall back to the
721 -- family tycon (with indexes) in error messages.
722
723 data DerivStatus = CanDerive
724                  | DerivableClassError SDoc     -- Standard class, but can't do it
725                  | NonDerivableClass            -- Non-standard class
726
727 checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> DerivStatus
728 checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
729   | Just cond <- sideConditions cls
730   = case (cond (mayDeriveDataTypeable, rep_tc)) of
731         Just err -> DerivableClassError err     -- Class-specific error
732         Nothing  | null cls_tys -> CanDerive
733                  | otherwise    -> DerivableClassError ty_args_why      -- e.g. deriving( Eq s )
734   | otherwise = NonDerivableClass       -- Not a standard class
735   where
736     ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "is not a class")
737
738 nonStdErr :: Class -> SDoc
739 nonStdErr cls = quotes (ppr cls) <+> ptext (sLit "is not a derivable class")
740
741 sideConditions :: Class -> Maybe Condition
742 sideConditions cls
743   | cls_key == eqClassKey      = Just cond_std
744   | cls_key == ordClassKey     = Just cond_std
745   | cls_key == showClassKey    = Just cond_std
746   | cls_key == readClassKey    = Just (cond_std `andCond` cond_noUnliftedArgs)
747   | cls_key == enumClassKey    = Just (cond_std `andCond` cond_isEnumeration)
748   | cls_key == ixClassKey      = Just (cond_std `andCond` cond_enumOrProduct)
749   | cls_key == boundedClassKey = Just (cond_std `andCond` cond_enumOrProduct)
750   | cls_key == dataClassKey    = Just (cond_mayDeriveDataTypeable `andCond` cond_std `andCond` cond_noUnliftedArgs)
751   | getName cls `elem` typeableClassNames = Just (cond_mayDeriveDataTypeable `andCond` cond_typeableOK)
752   | otherwise = Nothing
753   where
754     cls_key = getUnique cls
755
756 type Condition = (Bool, TyCon) -> Maybe SDoc
757         -- Bool is whether or not we are allowed to derive Data and Typeable
758         -- TyCon is the *representation* tycon if the 
759         --      data type is an indexed one
760         -- Nothing => OK
761
762 orCond :: Condition -> Condition -> Condition
763 orCond c1 c2 tc 
764   = case c1 tc of
765         Nothing -> Nothing              -- c1 succeeds
766         Just x  -> case c2 tc of        -- c1 fails
767                      Nothing -> Nothing
768                      Just y  -> Just (x $$ ptext (sLit "  and") $$ y)
769                                         -- Both fail
770
771 andCond :: Condition -> Condition -> Condition
772 andCond c1 c2 tc = case c1 tc of
773                      Nothing -> c2 tc   -- c1 succeeds
774                      Just x  -> Just x  -- c1 fails
775
776 cond_std :: Condition
777 cond_std (_, rep_tc)
778   | any (not . isVanillaDataCon) data_cons = Just existential_why     
779   | null data_cons                         = Just no_cons_why
780   | otherwise                              = Nothing
781   where
782     data_cons       = tyConDataCons rep_tc
783     no_cons_why     = quotes (pprSourceTyCon rep_tc) <+> 
784                       ptext (sLit "has no data constructors")
785     existential_why = quotes (pprSourceTyCon rep_tc) <+> 
786                       ptext (sLit "has non-Haskell-98 constructor(s)")
787   
788 cond_enumOrProduct :: Condition
789 cond_enumOrProduct = cond_isEnumeration `orCond` 
790                        (cond_isProduct `andCond` cond_noUnliftedArgs)
791
792 cond_noUnliftedArgs :: Condition
793 -- For some classes (eg Eq, Ord) we allow unlifted arg types
794 -- by generating specilaised code.  For others (eg Data) we don't.
795 cond_noUnliftedArgs (_, tc)
796   | null bad_cons = Nothing
797   | otherwise     = Just why
798   where
799     bad_cons = [ con | con <- tyConDataCons tc
800                      , any isUnLiftedType (dataConOrigArgTys con) ]
801     why = ptext (sLit "Constructor") <+> quotes (ppr (head bad_cons))
802           <+> ptext (sLit "has arguments of unlifted type")
803
804 cond_isEnumeration :: Condition
805 cond_isEnumeration (_, rep_tc)
806   | isEnumerationTyCon rep_tc = Nothing
807   | otherwise                 = Just why
808   where
809     why = quotes (pprSourceTyCon rep_tc) <+> 
810           ptext (sLit "has non-nullary constructors")
811
812 cond_isProduct :: Condition
813 cond_isProduct (_, rep_tc)
814   | isProductTyCon rep_tc = Nothing
815   | otherwise             = Just why
816   where
817     why = quotes (pprSourceTyCon rep_tc) <+> 
818           ptext (sLit "has more than one constructor")
819
820 cond_typeableOK :: Condition
821 -- OK for Typeable class
822 -- Currently: (a) args all of kind *
823 --            (b) 7 or fewer args
824 cond_typeableOK (_, rep_tc)
825   | tyConArity rep_tc > 7       = Just too_many
826   | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc)) 
827                                 = Just bad_kind
828   | isFamInstTyCon rep_tc       = Just fam_inst  -- no Typable for family insts
829   | otherwise                   = Nothing
830   where
831     too_many = quotes (pprSourceTyCon rep_tc) <+> 
832                ptext (sLit "has too many arguments")
833     bad_kind = quotes (pprSourceTyCon rep_tc) <+> 
834                ptext (sLit "has arguments of kind other than `*'")
835     fam_inst = quotes (pprSourceTyCon rep_tc) <+> 
836                ptext (sLit "is a type family")
837
838 cond_mayDeriveDataTypeable :: Condition
839 cond_mayDeriveDataTypeable (mayDeriveDataTypeable, _)
840  | mayDeriveDataTypeable = Nothing
841  | otherwise = Just why
842   where
843     why  = ptext (sLit "You need -XDeriveDataTypeable to derive an instance for this class")
844
845 std_class_via_iso :: Class -> Bool
846 std_class_via_iso clas  -- These standard classes can be derived for a newtype
847                         -- using the isomorphism trick *even if no -fglasgow-exts*
848   = classKey clas `elem`  [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
849         -- Not Read/Show because they respect the type
850         -- Not Enum, because newtypes are never in Enum
851
852
853 new_dfun_name :: Class -> TyCon -> TcM Name
854 new_dfun_name clas tycon        -- Just a simple wrapper
855   = do { loc <- getSrcSpanM     -- The location of the instance decl, not of the tycon
856         ; newDFunName clas [mkTyConApp tycon []] loc }
857         -- The type passed to newDFunName is only used to generate
858         -- a suitable string; hence the empty type arg list
859 \end{code}
860
861 Note [Superclasses of derived instance] 
862 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
863 In general, a derived instance decl needs the superclasses of the derived
864 class too.  So if we have
865         data T a = ...deriving( Ord )
866 then the initial context for Ord (T a) should include Eq (T a).  Often this is 
867 redundant; we'll also generate an Ord constraint for each constructor argument,
868 and that will probably generate enough constraints to make the Eq (T a) constraint 
869 be satisfied too.  But not always; consider:
870
871  data S a = S
872  instance Eq (S a)
873  instance Ord (S a)
874
875  data T a = MkT (S a) deriving( Ord )
876  instance Num a => Eq (T a)
877
878 The derived instance for (Ord (T a)) must have a (Num a) constraint!
879 Similarly consider:
880         data T a = MkT deriving( Data, Typeable )
881 Here there *is* no argument field, but we must nevertheless generate
882 a context for the Data instances:
883         instance Typable a => Data (T a) where ...
884
885
886 %************************************************************************
887 %*                                                                      *
888                 Deriving newtypes
889 %*                                                                      *
890 %************************************************************************
891
892 \begin{code}
893 mkNewTypeEqn :: InstOrigin -> Bool -> Bool -> [Var] -> Class
894              -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
895              -> Maybe ThetaType
896              -> TcRn EarlyDerivSpec
897 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving tvs
898              cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
899 -- Want: instance (...) => cls (cls_tys ++ [tycon tc_args]) where ...
900   | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
901   = do  { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
902         ; dfun_name <- new_dfun_name cls tycon
903         ; loc <- getSrcSpanM
904         ; let spec = DS { ds_loc = loc, ds_orig = orig
905                         , ds_name = dfun_name, ds_tvs = varSetElems dfun_tvs 
906                         , ds_cls = cls, ds_tys = inst_tys
907                         , ds_tc = rep_tycon, ds_tc_args = rep_tc_args
908                         , ds_theta =  mtheta `orElse` all_preds
909                         , ds_newtype = True }
910         ; return (if isJust mtheta then Right spec
911                                    else Left spec) }
912
913   | otherwise
914   = case check_conditions of
915       CanDerive -> mk_data_eqn orig tvs cls tycon tc_args rep_tycon rep_tc_args mtheta
916                                 -- Use the standard H98 method
917       DerivableClassError msg -> bale_out msg              -- Error with standard class
918       NonDerivableClass         -- Must use newtype deriving
919         | newtype_deriving    -> bale_out cant_derive_err  -- Too hard, even with newtype deriving
920         | otherwise           -> bale_out non_std_err      -- Try newtype deriving!
921   where
922         check_conditions = checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tycon
923         bale_out msg = failWithTc (derivingThingErr cls cls_tys inst_ty msg)
924
925         non_std_err = nonStdErr cls $$
926                       ptext (sLit "Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")
927
928         -- Here is the plan for newtype derivings.  We see
929         --        newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
930         -- where t is a type,
931         --       ak+1...an is a suffix of a1..an, and are all tyars
932         --       ak+1...an do not occur free in t, nor in the s1..sm
933         --       (C s1 ... sm) is a  *partial applications* of class C 
934         --                      with the last parameter missing
935         --       (T a1 .. ak) matches the kind of C's last argument
936         --              (and hence so does t)
937         -- The latter kind-check has been done by deriveTyData already,
938         -- and tc_args are already trimmed
939         --
940         -- We generate the instance
941         --       instance forall ({a1..ak} u fvs(s1..sm)).
942         --                C s1 .. sm t => C s1 .. sm (T a1...ak)
943         -- where T a1...ap is the partial application of 
944         --       the LHS of the correct kind and p >= k
945         --
946         --      NB: the variables below are:
947         --              tc_tvs = [a1, ..., an]
948         --              tyvars_to_keep = [a1, ..., ak]
949         --              rep_ty = t ak .. an
950         --              deriv_tvs = fvs(s1..sm) \ tc_tvs
951         --              tys = [s1, ..., sm]
952         --              rep_fn' = t
953         --
954         -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
955         -- We generate the instance
956         --      instance Monad (ST s) => Monad (T s) where 
957
958         nt_eta_arity = length (fst (newTyConEtadRhs rep_tycon))
959                 -- For newtype T a b = MkT (S a a b), the TyCon machinery already
960                 -- eta-reduces the representation type, so we know that
961                 --      T a ~ S a a
962                 -- That's convenient here, because we may have to apply
963                 -- it to fewer than its original complement of arguments
964
965         -- Note [Newtype representation]
966         -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
967         -- Need newTyConRhs (*not* a recursive representation finder) 
968         -- to get the representation type. For example
969         --      newtype B = MkB Int
970         --      newtype A = MkA B deriving( Num )
971         -- We want the Num instance of B, *not* the Num instance of Int,
972         -- when making the Num instance of A!
973         rep_inst_ty = newTyConInstRhs rep_tycon rep_tc_args
974         rep_tys     = cls_tys ++ [rep_inst_ty]
975         rep_pred    = mkClassPred cls rep_tys
976                 -- rep_pred is the representation dictionary, from where
977                 -- we are gong to get all the methods for the newtype
978                 -- dictionary 
979
980
981     -- Next we figure out what superclass dictionaries to use
982     -- See Note [Newtype deriving superclasses] above
983
984         cls_tyvars = classTyVars cls
985         dfun_tvs = tyVarsOfTypes inst_tys
986         inst_ty = mkTyConApp tycon tc_args
987         inst_tys = cls_tys ++ [inst_ty]
988         sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
989                               (classSCTheta cls)
990
991                 -- If there are no tyvars, there's no need
992                 -- to abstract over the dictionaries we need
993                 -- Example:     newtype T = MkT Int deriving( C )
994                 -- We get the derived instance
995                 --              instance C T
996                 -- rather than
997                 --              instance C Int => C T
998         all_preds = rep_pred : sc_theta         -- NB: rep_pred comes first
999
1000         -------------------------------------------------------------------
1001         --  Figuring out whether we can only do this newtype-deriving thing
1002
1003         right_arity = length cls_tys + 1 == classArity cls
1004
1005                 -- Never derive Read,Show,Typeable,Data this way 
1006         non_iso_class cls = className cls `elem` ([readClassName, showClassName, dataClassName] ++
1007                                                   typeableClassNames)
1008         can_derive_via_isomorphism
1009            =  not (non_iso_class cls)
1010            && right_arity                       -- Well kinded;
1011                                                 -- eg not: newtype T ... deriving( ST )
1012                                                 --      because ST needs *2* type params
1013            && eta_ok                            -- Eta reduction works
1014 --         && not (isRecursiveTyCon tycon)      -- Note [Recursive newtypes]
1015
1016         -- Check that eta reduction is OK
1017         eta_ok = nt_eta_arity <= length rep_tc_args
1018                 -- The newtype can be eta-reduced to match the number
1019                 --     of type argument actually supplied
1020                 --        newtype T a b = MkT (S [a] b) deriving( Monad )
1021                 --     Here the 'b' must be the same in the rep type (S [a] b)
1022                 --     And the [a] must not mention 'b'.  That's all handled
1023                 --     by nt_eta_rity.
1024
1025         cant_derive_err = vcat [ptext (sLit "even with cunning newtype deriving:"),
1026                                 if isRecursiveTyCon tycon then
1027                                   ptext (sLit "the newtype may be recursive")
1028                                 else empty,
1029                                 if not right_arity then 
1030                                   quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "does not have arity 1")
1031                                 else empty,
1032                                 if not eta_ok then 
1033                                   ptext (sLit "cannot eta-reduce the representation type enough")
1034                                 else empty
1035                                 ]
1036 \end{code}
1037
1038 Note [Recursive newtypes]
1039 ~~~~~~~~~~~~~~~~~~~~~~~~~
1040 Newtype deriving works fine, even if the newtype is recursive.
1041 e.g.    newtype S1 = S1 [T1 ()]
1042         newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
1043 Remember, too, that type families are curretly (conservatively) given
1044 a recursive flag, so this also allows newtype deriving to work
1045 for type famillies.
1046
1047 We used to exclude recursive types, because we had a rather simple
1048 minded way of generating the instance decl:
1049    newtype A = MkA [A]
1050    instance Eq [A] => Eq A      -- Makes typechecker loop!
1051 But now we require a simple context, so it's ok.
1052
1053
1054 %************************************************************************
1055 %*                                                                      *
1056 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
1057 %*                                                                      *
1058 %************************************************************************
1059
1060 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
1061 terms, which is the final correct RHS for the corresponding original
1062 equation.
1063 \begin{itemize}
1064 \item
1065 Each (k,TyVarTy tv) in a solution constrains only a type
1066 variable, tv.
1067
1068 \item
1069 The (k,TyVarTy tv) pairs in a solution are canonically
1070 ordered by sorting on type varible, tv, (major key) and then class, k,
1071 (minor key)
1072 \end{itemize}
1073
1074 \begin{code}
1075 inferInstanceContexts :: OverlapFlag -> [DerivSpec] -> TcM [DerivSpec]
1076
1077 inferInstanceContexts _ [] = return []
1078
1079 inferInstanceContexts oflag infer_specs
1080   = do  { traceTc (text "inferInstanceContexts" <+> vcat (map pprDerivSpec infer_specs))
1081         ; iterate_deriv 1 initial_solutions }
1082   where
1083     ------------------------------------------------------------------
1084         -- The initial solutions for the equations claim that each
1085         -- instance has an empty context; this solution is certainly
1086         -- in canonical form.
1087     initial_solutions :: [ThetaType]
1088     initial_solutions = [ [] | _ <- infer_specs ]
1089
1090     ------------------------------------------------------------------
1091         -- iterate_deriv calculates the next batch of solutions,
1092         -- compares it with the current one; finishes if they are the
1093         -- same, otherwise recurses with the new solutions.
1094         -- It fails if any iteration fails
1095     iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec]
1096     iterate_deriv n current_solns
1097       | n > 20  -- Looks as if we are in an infinite loop
1098                 -- This can happen if we have -XUndecidableInstances
1099                 -- (See TcSimplify.tcSimplifyDeriv.)
1100       = pprPanic "solveDerivEqns: probable loop" 
1101                  (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
1102       | otherwise
1103       = do {      -- Extend the inst info from the explicit instance decls
1104                   -- with the current set of solutions, and simplify each RHS
1105              let inst_specs = zipWithEqual "add_solns" (mkInstance oflag)
1106                                            current_solns infer_specs
1107            ; new_solns <- checkNoErrs $
1108                           extendLocalInstEnv inst_specs $
1109                           mapM gen_soln infer_specs
1110
1111            ; if (current_solns == new_solns) then
1112                 return [ spec { ds_theta = soln } 
1113                        | (spec, soln) <- zip infer_specs current_solns ]
1114              else
1115                 iterate_deriv (n+1) new_solns }
1116
1117     ------------------------------------------------------------------
1118     gen_soln :: DerivSpec  -> TcM [PredType]
1119     gen_soln (DS { ds_loc = loc, ds_orig = orig, ds_tvs = tyvars 
1120                  , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
1121       = setSrcSpan loc  $
1122         addErrCtxt (derivInstCtxt clas inst_tys) $ 
1123         do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
1124                 -- checkValidInstance tyvars theta clas inst_tys
1125                 -- Not necessary; see Note [Exotic derived instance contexts]
1126                 --                in TcSimplify
1127
1128                   -- Check for a bizarre corner case, when the derived instance decl should
1129                   -- have form  instance C a b => D (T a) where ...
1130                   -- Note that 'b' isn't a parameter of T.  This gives rise to all sorts
1131                   -- of problems; in particular, it's hard to compare solutions for
1132                   -- equality when finding the fixpoint.  So I just rule it out for now.
1133            ; let tv_set = mkVarSet tyvars
1134                  weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]  
1135            ; mapM_ (addErrTc . badDerivedPred) weird_preds      
1136
1137                 -- Claim: the result instance declaration is guaranteed valid
1138                 -- Hence no need to call:
1139                 --   checkValidInstance tyvars theta clas inst_tys
1140            ; return (sortLe (<=) theta) }       -- Canonicalise before returning the solution
1141
1142 ------------------------------------------------------------------
1143 mkInstance :: OverlapFlag -> ThetaType -> DerivSpec -> Instance
1144 mkInstance overlap_flag theta
1145             (DS { ds_name = dfun_name
1146                 , ds_tvs = tyvars, ds_cls = clas, ds_tys = tys })
1147   = mkLocalInstance dfun overlap_flag
1148   where
1149     dfun = mkDictFunId dfun_name tyvars theta clas tys
1150
1151
1152 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
1153 -- Add new locally-defined instances; don't bother to check
1154 -- for functional dependency errors -- that'll happen in TcInstDcls
1155 extendLocalInstEnv dfuns thing_inside
1156  = do { env <- getGblEnv
1157       ; let  inst_env' = extendInstEnvList (tcg_inst_env env) dfuns 
1158              env'      = env { tcg_inst_env = inst_env' }
1159       ; setGblEnv env' thing_inside }
1160 \end{code}
1161
1162
1163 %************************************************************************
1164 %*                                                                      *
1165 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
1166 %*                                                                      *
1167 %************************************************************************
1168
1169 After all the trouble to figure out the required context for the
1170 derived instance declarations, all that's left is to chug along to
1171 produce them.  They will then be shoved into @tcInstDecls2@, which
1172 will do all its usual business.
1173
1174 There are lots of possibilities for code to generate.  Here are
1175 various general remarks.
1176
1177 PRINCIPLES:
1178 \begin{itemize}
1179 \item
1180 We want derived instances of @Eq@ and @Ord@ (both v common) to be
1181 ``you-couldn't-do-better-by-hand'' efficient.
1182
1183 \item
1184 Deriving @Show@---also pretty common--- should also be reasonable good code.
1185
1186 \item
1187 Deriving for the other classes isn't that common or that big a deal.
1188 \end{itemize}
1189
1190 PRAGMATICS:
1191
1192 \begin{itemize}
1193 \item
1194 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
1195
1196 \item
1197 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
1198
1199 \item
1200 We {\em normally} generate code only for the non-defaulted methods;
1201 there are some exceptions for @Eq@ and (especially) @Ord@...
1202
1203 \item
1204 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
1205 constructor's numeric (@Int#@) tag.  These are generated by
1206 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
1207 these is around is given by @hasCon2TagFun@.
1208
1209 The examples under the different sections below will make this
1210 clearer.
1211
1212 \item
1213 Much less often (really just for deriving @Ix@), we use a
1214 @_tag2con_<tycon>@ function.  See the examples.
1215
1216 \item
1217 We use the renamer!!!  Reason: we're supposed to be
1218 producing @LHsBinds Name@ for the methods, but that means
1219 producing correctly-uniquified code on the fly.  This is entirely
1220 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
1221 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
1222 the renamer.  What a great hack!
1223 \end{itemize}
1224
1225 \begin{code}
1226 -- Generate the InstInfo for the required instance paired with the
1227 --   *representation* tycon for that instance,
1228 -- plus any auxiliary bindings required
1229 --
1230 -- Representation tycons differ from the tycon in the instance signature in
1231 -- case of instances for indexed families.
1232 --
1233 genInst :: OverlapFlag -> DerivSpec -> TcM (InstInfo RdrName, DerivAuxBinds)
1234 genInst oflag spec
1235   | ds_newtype spec
1236   = return (InstInfo { iSpec  = mkInstance oflag (ds_theta spec) spec
1237                      , iBinds = NewTypeDerived co }, [])
1238
1239   | otherwise
1240   = do  { let loc        = getSrcSpan (ds_name spec)
1241               inst       = mkInstance oflag (ds_theta spec) spec
1242               clas       = ds_cls spec
1243
1244           -- In case of a family instance, we need to use the representation
1245           -- tycon (after all, it has the data constructors)
1246         ; fix_env <- getFixityEnv
1247         ; let (meth_binds, aux_binds) = genDerivBinds loc fix_env clas rep_tycon
1248
1249         -- Build the InstInfo
1250         ; return (InstInfo { iSpec = inst, 
1251                              iBinds = VanillaInst meth_binds [] },
1252                   aux_binds)
1253         }
1254   where
1255     rep_tycon   = ds_tc spec
1256     rep_tc_args = ds_tc_args spec
1257     co1 = case tyConFamilyCoercion_maybe rep_tycon of
1258               Nothing     -> IdCo
1259               Just co_con -> ACo (mkTyConApp co_con rep_tc_args)
1260     co2 = case newTyConCo_maybe rep_tycon of
1261               Nothing     -> IdCo       -- The newtype is transparent; no need for a cast
1262               Just co_con -> ACo (mkTyConApp co_con rep_tc_args)
1263     co = co1 `mkTransCoI` co2
1264
1265 -- Example: newtype instance N [a] = N1 (Tree a) 
1266 --          deriving instance Eq b => Eq (N [(b,b)])
1267 -- From the instance, we get an implicit newtype R1:N a = N1 (Tree a)
1268 -- When dealing with the deriving clause
1269 --    co1 : N [(b,b)] ~ R1:N (b,b)
1270 --    co2 : R1:N (b,b) ~ Tree (b,b)
1271
1272 genDerivBinds :: SrcSpan -> FixityEnv -> Class -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1273 genDerivBinds loc fix_env clas tycon
1274   | className clas `elem` typeableClassNames
1275   = (gen_Typeable_binds loc tycon, [])
1276
1277   | otherwise
1278   = case assocMaybe gen_list (getUnique clas) of
1279         Just gen_fn -> gen_fn loc tycon
1280         Nothing     -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1281   where
1282     gen_list :: [(Unique, SrcSpan -> TyCon -> (LHsBinds RdrName, DerivAuxBinds))]
1283     gen_list = [(eqClassKey,       gen_Eq_binds)
1284                ,(ordClassKey,      gen_Ord_binds)
1285                ,(enumClassKey,     gen_Enum_binds)
1286                ,(boundedClassKey,  gen_Bounded_binds)
1287                ,(ixClassKey,       gen_Ix_binds)
1288                ,(showClassKey,     gen_Show_binds fix_env)
1289                ,(readClassKey,     gen_Read_binds fix_env)
1290                ,(dataClassKey,     gen_Data_binds)
1291                ]
1292 \end{code}
1293
1294
1295 %************************************************************************
1296 %*                                                                      *
1297 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1298 %*                                                                      *
1299 %************************************************************************
1300
1301 \begin{code}
1302 derivingKindErr :: TyCon -> Class -> [Type] -> Kind -> Message
1303 derivingKindErr tc cls cls_tys cls_kind
1304   = hang (ptext (sLit "Cannot derive well-kinded instance of form")
1305                 <+> quotes (pprClassPred cls cls_tys <+> parens (ppr tc <+> ptext (sLit "..."))))
1306        2 (ptext (sLit "Class") <+> quotes (ppr cls)
1307             <+> ptext (sLit "expects an argument of kind") <+> quotes (pprKind cls_kind))
1308
1309 derivingEtaErr :: Class -> [Type] -> Type -> Message
1310 derivingEtaErr cls cls_tys inst_ty
1311   = sep [ptext (sLit "Cannot eta-reduce to an instance of form"),
1312          nest 2 (ptext (sLit "instance (...) =>")
1313                 <+> pprClassPred cls (cls_tys ++ [inst_ty]))]
1314
1315 typeFamilyPapErr :: TyCon -> Class -> [Type] -> Type -> Message
1316 typeFamilyPapErr tc cls cls_tys inst_ty
1317   = hang (ptext (sLit "Derived instance") <+> quotes (pprClassPred cls (cls_tys ++ [inst_ty])))
1318        2 (ptext (sLit "requires illegal partial application of data type family") <+> ppr tc) 
1319
1320 derivingThingErr :: Class -> [Type] -> Type -> Message -> Message
1321 derivingThingErr clas tys ty why
1322   = sep [hsep [ptext (sLit "Can't make a derived instance of"), 
1323                quotes (ppr pred)],
1324          nest 2 (parens why)]
1325   where
1326     pred = mkClassPred clas (tys ++ [ty])
1327
1328 derivingHiddenErr :: TyCon -> SDoc
1329 derivingHiddenErr tc
1330   = hang (ptext (sLit "The data constructors of") <+> quotes (ppr tc) <+> ptext (sLit "are not all in scope"))
1331        2 (ptext (sLit "so you cannot derive an instance for it"))
1332
1333 standaloneCtxt :: LHsType Name -> SDoc
1334 standaloneCtxt ty = hang (ptext (sLit "In the stand-alone deriving instance for")) 
1335                        2 (quotes (ppr ty))
1336
1337 derivInstCtxt :: Class -> [Type] -> Message
1338 derivInstCtxt clas inst_tys
1339   = ptext (sLit "When deriving the instance for") <+> parens (pprClassPred clas inst_tys)
1340
1341 badDerivedPred :: PredType -> Message
1342 badDerivedPred pred
1343   = vcat [ptext (sLit "Can't derive instances where the instance context mentions"),
1344           ptext (sLit "type variables that are not data type parameters"),
1345           nest 2 (ptext (sLit "Offending constraint:") <+> ppr pred)]
1346 \end{code}