[project @ 2003-10-09 11:58:39 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcDeriv.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcDeriv]{Deriving}
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            ( HsBinds(..), TyClDecl(..), MonoBinds(..),
14                           andMonoBindList )
15 import RdrHsSyn         ( RdrNameMonoBinds )
16 import RnHsSyn          ( RenamedHsBinds, RenamedTyClDecl, RenamedHsPred )
17 import CmdLineOpts      ( DynFlag(..) )
18
19 import Generics         ( mkGenericBinds )
20 import TcRnMonad
21 import TcEnv            ( newDFunName, 
22                           InstInfo(..), pprInstInfo, InstBindings(..),
23                           pprInstInfoDetails, tcLookupTyCon, tcExtendTyVarEnv
24                         )
25 import TcGenDeriv       -- Deriv stuff
26 import InstEnv          ( simpleDFunClassTyCon, extendInstEnv )
27 import TcHsType         ( tcHsPred )
28 import TcSimplify       ( tcSimplifyDeriv )
29
30 import RnBinds          ( rnMethodBinds, rnTopMonoBinds )
31 import RnEnv            ( bindLocalNames )
32 import TcRnMonad        ( thenM, returnM, mapAndUnzipM )
33 import HscTypes         ( DFunId, FixityEnv, typeEnvTyCons )
34
35 import BasicTypes       ( NewOrData(..) )
36 import Class            ( className, classArity, classKey, classTyVars, classSCTheta, Class )
37 import Subst            ( mkTyVarSubst, substTheta )
38 import ErrUtils         ( dumpIfSet_dyn )
39 import MkId             ( mkDictFunId )
40 import DataCon          ( dataConOrigArgTys, isNullaryDataCon, isExistentialDataCon )
41 import Maybes           ( catMaybes )
42 import Name             ( Name, getSrcLoc )
43 import Unique           ( Unique, getUnique )
44
45 import TyCon            ( tyConTyVars, tyConDataCons, tyConArity, 
46                           tyConTheta, isProductTyCon, isDataTyCon,
47                           isEnumerationTyCon, isRecursiveTyCon, TyCon
48                         )
49 import TcType           ( TcType, ThetaType, mkTyVarTy, mkTyVarTys, mkTyConApp, 
50                           getClassPredTys_maybe, tcTyConAppTyCon,
51                           isUnLiftedType, mkClassPred, tyVarsOfTypes, tcSplitFunTys, isTypeKind,
52                           tcEqTypes, tcSplitAppTys, mkAppTys, tcSplitDFunTy )
53 import Var              ( TyVar, tyVarKind, idType, varName )
54 import VarSet           ( mkVarSet, subVarSet )
55 import PrelNames
56 import Util             ( zipWithEqual, sortLt, notNull )
57 import ListSetOps       ( removeDups,  assoc )
58 import Outputable
59 \end{code}
60
61 %************************************************************************
62 %*                                                                      *
63 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
64 %*                                                                      *
65 %************************************************************************
66
67 Consider
68
69         data T a b = C1 (Foo a) (Bar b)
70                    | C2 Int (T b a)
71                    | C3 (T a a)
72                    deriving (Eq)
73
74 [NOTE: See end of these comments for what to do with 
75         data (C a, D b) => T a b = ...
76 ]
77
78 We want to come up with an instance declaration of the form
79
80         instance (Ping a, Pong b, ...) => Eq (T a b) where
81                 x == y = ...
82
83 It is pretty easy, albeit tedious, to fill in the code "...".  The
84 trick is to figure out what the context for the instance decl is,
85 namely @Ping@, @Pong@ and friends.
86
87 Let's call the context reqd for the T instance of class C at types
88 (a,b, ...)  C (T a b).  Thus:
89
90         Eq (T a b) = (Ping a, Pong b, ...)
91
92 Now we can get a (recursive) equation from the @data@ decl:
93
94         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
95                    u Eq (T b a) u Eq Int        -- From C2
96                    u Eq (T a a)                 -- From C3
97
98 Foo and Bar may have explicit instances for @Eq@, in which case we can
99 just substitute for them.  Alternatively, either or both may have
100 their @Eq@ instances given by @deriving@ clauses, in which case they
101 form part of the system of equations.
102
103 Now all we need do is simplify and solve the equations, iterating to
104 find the least fixpoint.  Notice that the order of the arguments can
105 switch around, as here in the recursive calls to T.
106
107 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
108
109 We start with:
110
111         Eq (T a b) = {}         -- The empty set
112
113 Next iteration:
114         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
115                    u Eq (T b a) u Eq Int        -- From C2
116                    u Eq (T a a)                 -- From C3
117
118         After simplification:
119                    = Eq a u Ping b u {} u {} u {}
120                    = Eq a u Ping b
121
122 Next iteration:
123
124         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
125                    u Eq (T b a) u Eq Int        -- From C2
126                    u Eq (T a a)                 -- From C3
127
128         After simplification:
129                    = Eq a u Ping b
130                    u (Eq b u Ping a)
131                    u (Eq a u Ping a)
132
133                    = Eq a u Ping b u Eq b u Ping a
134
135 The next iteration gives the same result, so this is the fixpoint.  We
136 need to make a canonical form of the RHS to ensure convergence.  We do
137 this by simplifying the RHS to a form in which
138
139         - the classes constrain only tyvars
140         - the list is sorted by tyvar (major key) and then class (minor key)
141         - no duplicates, of course
142
143 So, here are the synonyms for the ``equation'' structures:
144
145 \begin{code}
146 type DerivEqn = (Name, Class, TyCon, [TyVar], DerivRhs)
147                 -- The Name is the name for the DFun we'll build
148                 -- The tyvars bind all the variables in the RHS
149
150 pprDerivEqn (n,c,tc,tvs,rhs)
151   = parens (hsep [ppr n, ppr c, ppr tc, ppr tvs] <+> equals <+> ppr rhs)
152
153 type DerivRhs  = ThetaType
154 type DerivSoln = DerivRhs
155 \end{code}
156
157
158 [Data decl contexts] A note about contexts on data decls
159 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
160 Consider
161
162         data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
163
164 We will need an instance decl like:
165
166         instance (Read a, RealFloat a) => Read (Complex a) where
167           ...
168
169 The RealFloat in the context is because the read method for Complex is bound
170 to construct a Complex, and doing that requires that the argument type is
171 in RealFloat. 
172
173 But this ain't true for Show, Eq, Ord, etc, since they don't construct
174 a Complex; they only take them apart.
175
176 Our approach: identify the offending classes, and add the data type
177 context to the instance decl.  The "offending classes" are
178
179         Read, Enum?
180
181 FURTHER NOTE ADDED March 2002.  In fact, Haskell98 now requires that
182 pattern matching against a constructor from a data type with a context
183 gives rise to the constraints for that context -- or at least the thinned
184 version.  So now all classes are "offending".
185
186
187
188 %************************************************************************
189 %*                                                                      *
190 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
191 %*                                                                      *
192 %************************************************************************
193
194 \begin{code}
195 tcDeriving  :: [RenamedTyClDecl]        -- All type constructors
196             -> TcM ([InstInfo],         -- The generated "instance decls"
197                     RenamedHsBinds)     -- Extra generated top-level bindings
198
199 tcDeriving tycl_decls
200   = recoverM (returnM ([], EmptyBinds)) $
201     getDOpts                    `thenM` \ dflags ->
202
203         -- Fish the "deriving"-related information out of the TcEnv
204         -- and make the necessary "equations".
205     makeDerivEqns tycl_decls                            `thenM` \ (ordinary_eqns, newtype_inst_info) ->
206     extendLocalInstEnv (map iDFunId newtype_inst_info)  $
207         -- Add the newtype-derived instances to the inst env
208         -- before tacking the "ordinary" ones
209
210     deriveOrdinaryStuff ordinary_eqns                   `thenM` \ (ordinary_inst_info, binds) ->
211     let
212         inst_info  = newtype_inst_info ++ ordinary_inst_info
213     in
214
215     ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances" 
216              (ddump_deriving inst_info binds))          `thenM_`
217
218     returnM (inst_info, binds)
219
220   where
221     ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
222     ddump_deriving inst_infos extra_binds
223       = vcat (map ppr_info inst_infos) $$ ppr extra_binds
224
225     ppr_info inst_info = pprInstInfo inst_info $$ 
226                          nest 4 (pprInstInfoDetails inst_info)
227         -- pprInstInfo doesn't print much: only the type
228
229 -----------------------------------------
230 deriveOrdinaryStuff []  -- Short cut
231   = returnM ([], EmptyBinds)
232
233 deriveOrdinaryStuff eqns
234   = do  {       -- Take the equation list and solve it, to deliver a list of
235                 -- solutions, a.k.a. the contexts for the instance decls
236                 -- required for the corresponding equations.
237         ; new_dfuns <- solveDerivEqns eqns
238
239         -- Generate the InstInfo for each dfun, 
240         -- plus any auxiliary bindings it needs
241         ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst new_dfuns
242
243         -- Generate any extra not-one-inst-decl-specific binds, 
244         -- notably "con2tag" and/or "tag2con" functions.  
245         ; extra_binds <- genTaggeryBinds new_dfuns
246
247         -- Generate the generic to/from functions from each type declaration
248         ; tcg_env <- getGblEnv
249         ; let gen_binds = mkGenericBinds (typeEnvTyCons (tcg_type_env tcg_env))
250
251         -- Rename these extra bindings
252         ; (rn_binds, _fvs1) <- rnTopMonoBinds (extra_binds `AndMonoBinds` gen_binds) []
253
254         ; let all_binds = rn_binds `ThenBinds` 
255                           foldr ThenBinds EmptyBinds aux_binds_s
256
257         -- Done
258         ; traceTc (text "tcDeriv" <+> vcat (map pprInstInfo inst_infos))
259         ; returnM (inst_infos, all_binds) }
260 \end{code}
261
262
263 %************************************************************************
264 %*                                                                      *
265 \subsection[TcDeriv-eqns]{Forming the equations}
266 %*                                                                      *
267 %************************************************************************
268
269 @makeDerivEqns@ fishes around to find the info about needed derived
270 instances.  Complicating factors:
271 \begin{itemize}
272 \item
273 We can only derive @Enum@ if the data type is an enumeration
274 type (all nullary data constructors).
275
276 \item
277 We can only derive @Ix@ if the data type is an enumeration {\em
278 or} has just one data constructor (e.g., tuples).
279 \end{itemize}
280
281 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
282 all those.
283
284 \begin{code}
285 makeDerivEqns :: [RenamedTyClDecl] 
286               -> TcM ([DerivEqn],       -- Ordinary derivings
287                       [InstInfo])       -- Special newtype derivings
288
289 makeDerivEqns tycl_decls
290   = mapAndUnzipM mk_eqn derive_these            `thenM` \ (maybe_ordinaries, maybe_newtypes) ->
291     returnM (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
292   where
293     ------------------------------------------------------------------
294     derive_these :: [(NewOrData, Name, RenamedHsPred)]
295         -- Find the (nd, TyCon, Pred) pairs that must be `derived'
296         -- NB: only source-language decls have deriving, no imported ones do
297     derive_these = [ (nd, tycon, pred) 
298                    | TyData {tcdND = nd, tcdName = tycon, tcdDerivs = Just preds} <- tycl_decls,
299                      pred <- preds ]
300
301     ------------------------------------------------------------------
302     mk_eqn :: (NewOrData, Name, RenamedHsPred) -> TcM (Maybe DerivEqn, Maybe InstInfo)
303         -- We swizzle the tyvars and datacons out of the tycon
304         -- to make the rest of the equation
305
306     mk_eqn (new_or_data, tycon_name, pred)
307       = tcLookupTyCon tycon_name                `thenM` \ tycon ->
308         addSrcLoc (getSrcLoc tycon)             $
309         addErrCtxt (derivCtxt Nothing tycon)    $
310         tcExtendTyVarEnv (tyConTyVars tycon)    $       -- Deriving preds may (now) mention
311                                                         -- the type variables for the type constructor
312         tcHsPred pred                           `thenM` \ pred' ->
313         case getClassPredTys_maybe pred' of
314            Nothing          -> bale_out (malformedPredErr tycon pred)
315            Just (clas, tys) -> doptM Opt_GlasgowExts                    `thenM` \ gla_exts ->
316                                mk_eqn_help gla_exts new_or_data tycon clas tys
317
318     ------------------------------------------------------------------
319     mk_eqn_help gla_exts DataType tycon clas tys
320       | Just err <- checkSideConditions gla_exts clas tycon tys
321       = bale_out (derivingThingErr clas tys tycon tyvars err)
322       | otherwise 
323       = new_dfun_name clas tycon         `thenM` \ dfun_name ->
324         returnM (Just (dfun_name, clas, tycon, tyvars, constraints), Nothing)
325       where
326         tyvars      = tyConTyVars tycon
327         constraints = extra_constraints ++ ordinary_constraints
328                  -- "extra_constraints": see note [Data decl contexts] above
329         extra_constraints = tyConTheta tycon
330
331         ordinary_constraints
332           | clas `hasKey` typeableClassKey      -- For the Typeable class, the constraints
333                                                 -- don't involve the constructor ags, only 
334                                                 -- the tycon tyvars
335                                                 -- e.g.   data T a b = ...
336                                                 -- we want
337                                                 --      instance (Typeable a, Typable b)
338                                                 --               => Typeable (T a b) where
339           = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
340           | otherwise
341           = [ mkClassPred clas [arg_ty] 
342             | data_con <- tyConDataCons tycon,
343               arg_ty   <- dataConOrigArgTys data_con,
344                         -- Use the same type variables
345                         -- as the type constructor,
346                         -- hence no need to instantiate
347               not (isUnLiftedType arg_ty)       -- No constraints for unlifted types?
348             ]
349
350     mk_eqn_help gla_exts NewType tycon clas tys
351       | can_derive_via_isomorphism && (gla_exts || standard_class gla_exts clas)
352       =         -- Go ahead and use the isomorphism
353            traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)     `thenM_`
354            new_dfun_name clas tycon             `thenM` \ dfun_name ->
355            returnM (Nothing, Just (InstInfo { iDFunId = mk_dfun dfun_name,
356                                               iBinds = NewTypeDerived rep_tys }))
357       | standard_class gla_exts clas
358       = mk_eqn_help gla_exts DataType tycon clas tys    -- Go via bale-out route
359
360       | otherwise                               -- Non-standard instance
361       = bale_out (if gla_exts then      
362                         cant_derive_err -- Too hard
363                   else
364                         non_std_err)    -- Just complain about being a non-std instance
365       where
366         -- Here is the plan for newtype derivings.  We see
367         --        newtype T a1...an = T (t ak...an) deriving (.., C s1 .. sm, ...)
368         -- where aj...an do not occur free in t, and the (C s1 ... sm) is a 
369         -- *partial applications* of class C with the last parameter missing
370         --
371         -- We generate the instances
372         --       instance C s1 .. sm (t ak...aj) => C s1 .. sm (T a1...aj)
373         -- where T a1...aj is the partial application of the LHS of the correct kind
374         --
375         -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
376         --      instance Monad (ST s) => Monad (T s) where 
377         --        fail = coerce ... (fail @ ST s)
378
379         clas_tyvars = classTyVars clas
380         kind = tyVarKind (last clas_tyvars)
381                 -- Kind of the thing we want to instance
382                 --   e.g. argument kind of Monad, *->*
383
384         (arg_kinds, _) = tcSplitFunTys kind
385         n_args_to_drop = length arg_kinds       
386                 -- Want to drop 1 arg from (T s a) and (ST s a)
387                 -- to get       instance Monad (ST s) => Monad (T s)
388
389         -- Note [newtype representation]
390         -- We must not use newTyConRep to get the representation 
391         -- type, because that looks through all intermediate newtypes
392         -- To get the RHS of *this* newtype, just look at the data
393         -- constructor.  For example
394         --      newtype B = MkB Int
395         --      newtype A = MkA B deriving( Num )
396         -- We want the Num instance of B, *not* the Num instance of Int,
397         -- when making the Num instance of A!
398         tyvars                = tyConTyVars tycon
399         rep_ty                = head (dataConOrigArgTys (head (tyConDataCons tycon)))
400         (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
401
402         n_tyvars_to_keep = tyConArity tycon  - n_args_to_drop
403         tyvars_to_drop   = drop n_tyvars_to_keep tyvars
404         tyvars_to_keep   = take n_tyvars_to_keep tyvars
405
406         n_args_to_keep = length rep_ty_args - n_args_to_drop
407         args_to_drop   = drop n_args_to_keep rep_ty_args
408         args_to_keep   = take n_args_to_keep rep_ty_args
409
410         rep_tys  = tys ++ [mkAppTys rep_fn args_to_keep]
411         rep_pred = mkClassPred clas rep_tys
412                 -- rep_pred is the representation dictionary, from where
413                 -- we are gong to get all the methods for the newtype dictionary
414
415         inst_tys = (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)])
416                 -- The 'tys' here come from the partial application
417                 -- in the deriving clause. The last arg is the new
418                 -- instance type.
419
420                 -- We must pass the superclasses; the newtype might be an instance
421                 -- of them in a different way than the representation type
422                 -- E.g.         newtype Foo a = Foo a deriving( Show, Num, Eq )
423                 -- Then the Show instance is not done via isomprphism; it shows
424                 --      Foo 3 as "Foo 3"
425                 -- The Num instance is derived via isomorphism, but the Show superclass
426                 -- dictionary must the Show instance for Foo, *not* the Show dictionary
427                 -- gotten from the Num dictionary. So we must build a whole new dictionary
428                 -- not just use the Num one.  The instance we want is something like:
429                 --      instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
430                 --              (+) = ((+)@a)
431                 --              ...etc...
432                 -- There's no 'corece' needed because after the type checker newtypes
433                 -- are transparent.
434
435         sc_theta = substTheta (mkTyVarSubst clas_tyvars inst_tys)
436                               (classSCTheta clas)
437
438                 -- If there are no tyvars, there's no need
439                 -- to abstract over the dictionaries we need
440         dict_args | null tyvars = []
441                   | otherwise   = rep_pred : sc_theta
442
443                 -- Finally! Here's where we build the dictionary Id
444         mk_dfun dfun_name = mkDictFunId dfun_name tyvars dict_args clas inst_tys
445
446         -------------------------------------------------------------------
447         --  Figuring out whether we can only do this newtype-deriving thing
448
449         right_arity = length tys + 1 == classArity clas
450
451                 -- Never derive Read,Show,Typeable,Data this way 
452         non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
453         can_derive_via_isomorphism
454            =  not (getUnique clas `elem` non_iso_classes)
455            && right_arity                       -- Well kinded;
456                                                 -- eg not: newtype T ... deriving( ST )
457                                                 --      because ST needs *2* type params
458            && n_tyvars_to_keep >= 0             -- Type constructor has right kind:
459                                                 -- eg not: newtype T = T Int deriving( Monad )
460            && n_args_to_keep   >= 0             -- Rep type has right kind: 
461                                                 -- eg not: newtype T a = T Int deriving( Monad )
462            && eta_ok                            -- Eta reduction works
463            && not (isRecursiveTyCon tycon)      -- Does not work for recursive tycons:
464                                                 --      newtype A = MkA [A]
465                                                 -- Don't want
466                                                 --      instance Eq [A] => Eq A !!
467
468                         -- Here's a recursive newtype that's actually OK
469                         --      newtype S1 = S1 [T1 ()]
470                         --      newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
471                         -- It's currently rejected.  Oh well.
472
473         -- Check that eta reduction is OK
474         --      (a) the dropped-off args are identical
475         --      (b) the remaining type args mention 
476         --          only the remaining type variables
477         eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
478               && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep) 
479
480         cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
481                                 (vcat [ptext SLIT("even with cunning newtype deriving:"),
482                                         if isRecursiveTyCon tycon then
483                                           ptext SLIT("the newtype is recursive")
484                                         else empty,
485                                         if not right_arity then 
486                                           quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1")
487                                         else empty,
488                                         if not (n_tyvars_to_keep >= 0) then 
489                                           ptext SLIT("the type constructor has wrong kind")
490                                         else if not (n_args_to_keep >= 0) then
491                                           ptext SLIT("the representation type has wrong kind")
492                                         else if not eta_ok then 
493                                           ptext SLIT("the eta-reduction property does not hold")
494                                         else empty
495                                       ])
496
497         non_std_err = derivingThingErr clas tys tycon tyvars_to_keep
498                                 (vcat [non_std_why clas,
499                                        ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
500
501     bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing) 
502     standard_class gla_exts clas =  key `elem` derivableClassKeys
503                                  || (gla_exts && (key == typeableClassKey || key == dataClassKey))
504         where
505           key = classKey clas
506
507
508
509
510 new_dfun_name clas tycon        -- Just a simple wrapper
511   = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
512         -- The type passed to newDFunName is only used to generate
513         -- a suitable string; hence the empty type arg list
514
515 ------------------------------------------------------------------
516 -- Check side conditions that dis-allow derivability for particular classes
517 -- This is *apart* from the newtype-deriving mechanism
518
519 checkSideConditions :: Bool -> Class -> TyCon -> [TcType] -> Maybe SDoc
520 checkSideConditions gla_exts clas tycon tys
521   | notNull tys 
522   = Just ty_args_why    -- e.g. deriving( Foo s )
523   | otherwise
524   = case [cond | (key,cond) <- sideConditions, key == getUnique clas] of
525         []     -> Just (non_std_why clas)
526         [cond] -> cond (gla_exts, tycon)
527         other  -> pprPanic "checkSideConditions" (ppr clas)
528   where
529     ty_args_why      = quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("is not a class")
530
531 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
532
533 sideConditions :: [(Unique, Condition)]
534 sideConditions
535   = [   (eqClassKey,       cond_std),
536         (ordClassKey,      cond_std),
537         (readClassKey,     cond_std),
538         (showClassKey,     cond_std),
539         (enumClassKey,     cond_std `andCond` cond_isEnumeration),
540         (ixClassKey,       cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
541         (boundedClassKey,  cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
542         (typeableClassKey, cond_glaExts `andCond` cond_allTypeKind),
543         (dataClassKey,     cond_glaExts `andCond` cond_std)
544     ]
545
546 type Condition = (Bool, TyCon) -> Maybe SDoc    -- Nothing => OK
547
548 orCond :: Condition -> Condition -> Condition
549 orCond c1 c2 tc 
550   = case c1 tc of
551         Nothing -> Nothing              -- c1 succeeds
552         Just x  -> case c2 tc of        -- c1 fails
553                      Nothing -> Nothing
554                      Just y  -> Just (x $$ ptext SLIT("  and") $$ y)
555                                         -- Both fail
556
557 andCond c1 c2 tc = case c1 tc of
558                      Nothing -> c2 tc   -- c1 succeeds
559                      Just x  -> Just x  -- c1 fails
560
561 cond_std :: Condition
562 cond_std (gla_exts, tycon)
563   | any isExistentialDataCon data_cons  = Just existential_why     
564   | null data_cons                      = Just no_cons_why
565   | otherwise                           = Nothing
566   where
567     data_cons       = tyConDataCons tycon
568     no_cons_why     = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
569     existential_why = quotes (ppr tycon) <+> ptext SLIT("has existentially-quantified constructor(s)")
570   
571 cond_isEnumeration :: Condition
572 cond_isEnumeration (gla_exts, tycon)
573   | isEnumerationTyCon tycon = Nothing
574   | otherwise                = Just why
575   where
576     why = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
577
578 cond_isProduct :: Condition
579 cond_isProduct (gla_exts, tycon)
580   | isProductTyCon tycon = Nothing
581   | otherwise            = Just why
582   where
583     why = quotes (ppr tycon) <+> ptext SLIT("has more than one constructor")
584
585 cond_allTypeKind :: Condition
586 cond_allTypeKind (gla_exts, tycon)
587   | all (isTypeKind . tyVarKind) (tyConTyVars tycon) = Nothing
588   | otherwise                                        = Just why
589   where
590     why  = quotes (ppr tycon) <+> ptext SLIT("is parameterised over arguments of kind other than `*'")
591
592 cond_glaExts :: Condition
593 cond_glaExts (gla_exts, tycon) | gla_exts  = Nothing
594                                | otherwise = Just why
595   where
596     why  = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
597 \end{code}
598
599 %************************************************************************
600 %*                                                                      *
601 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
602 %*                                                                      *
603 %************************************************************************
604
605 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
606 terms, which is the final correct RHS for the corresponding original
607 equation.
608 \begin{itemize}
609 \item
610 Each (k,TyVarTy tv) in a solution constrains only a type
611 variable, tv.
612
613 \item
614 The (k,TyVarTy tv) pairs in a solution are canonically
615 ordered by sorting on type varible, tv, (major key) and then class, k,
616 (minor key)
617 \end{itemize}
618
619 \begin{code}
620 solveDerivEqns :: [DerivEqn]
621                -> TcM [DFunId]  -- Solns in same order as eqns.
622                                 -- This bunch is Absolutely minimal...
623
624 solveDerivEqns orig_eqns
625   = iterateDeriv 1 initial_solutions
626   where
627         -- The initial solutions for the equations claim that each
628         -- instance has an empty context; this solution is certainly
629         -- in canonical form.
630     initial_solutions :: [DerivSoln]
631     initial_solutions = [ [] | _ <- orig_eqns ]
632
633     ------------------------------------------------------------------
634         -- iterateDeriv calculates the next batch of solutions,
635         -- compares it with the current one; finishes if they are the
636         -- same, otherwise recurses with the new solutions.
637         -- It fails if any iteration fails
638     iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
639     iterateDeriv n current_solns
640       | n > 20  -- Looks as if we are in an infinite loop
641                 -- This can happen if we have -fallow-undecidable-instances
642                 -- (See TcSimplify.tcSimplifyDeriv.)
643       = pprPanic "solveDerivEqns: probable loop" 
644                  (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
645       | otherwise
646       = let 
647             dfuns = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
648         in
649         checkNoErrs (
650                   -- Extend the inst info from the explicit instance decls
651                   -- with the current set of solutions, and simplify each RHS
652             extendLocalInstEnv dfuns $
653             mappM gen_soln orig_eqns
654         )                               `thenM` \ new_solns ->
655         if (current_solns == new_solns) then
656             returnM dfuns
657         else
658             iterateDeriv (n+1) new_solns
659
660     ------------------------------------------------------------------
661
662     gen_soln (_, clas, tc,tyvars,deriv_rhs)
663       = addSrcLoc (getSrcLoc tc)                $
664         addErrCtxt (derivCtxt (Just clas) tc)   $
665         tcSimplifyDeriv tyvars deriv_rhs        `thenM` \ theta ->
666         returnM (sortLt (<) theta)      -- Canonicalise before returning the soluction
667
668 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
669   = mkDictFunId dfun_name tyvars theta
670                 clas [mkTyConApp tycon (mkTyVarTys tyvars)] 
671
672 extendLocalInstEnv :: [DFunId] -> TcM a -> TcM a
673 -- Add new locall-defined instances; don't bother to check
674 -- for functional dependency errors -- that'll happen in TcInstDcls
675 extendLocalInstEnv dfuns thing_inside
676  = do { env <- getGblEnv
677       ; let  inst_env' = foldl extendInstEnv (tcg_inst_env env) dfuns 
678              env'      = env { tcg_inst_env = inst_env' }
679       ; setGblEnv env' thing_inside }
680 \end{code}
681
682 %************************************************************************
683 %*                                                                      *
684 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
685 %*                                                                      *
686 %************************************************************************
687
688 After all the trouble to figure out the required context for the
689 derived instance declarations, all that's left is to chug along to
690 produce them.  They will then be shoved into @tcInstDecls2@, which
691 will do all its usual business.
692
693 There are lots of possibilities for code to generate.  Here are
694 various general remarks.
695
696 PRINCIPLES:
697 \begin{itemize}
698 \item
699 We want derived instances of @Eq@ and @Ord@ (both v common) to be
700 ``you-couldn't-do-better-by-hand'' efficient.
701
702 \item
703 Deriving @Show@---also pretty common--- should also be reasonable good code.
704
705 \item
706 Deriving for the other classes isn't that common or that big a deal.
707 \end{itemize}
708
709 PRAGMATICS:
710
711 \begin{itemize}
712 \item
713 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
714
715 \item
716 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
717
718 \item
719 We {\em normally} generate code only for the non-defaulted methods;
720 there are some exceptions for @Eq@ and (especially) @Ord@...
721
722 \item
723 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
724 constructor's numeric (@Int#@) tag.  These are generated by
725 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
726 these is around is given by @hasCon2TagFun@.
727
728 The examples under the different sections below will make this
729 clearer.
730
731 \item
732 Much less often (really just for deriving @Ix@), we use a
733 @_tag2con_<tycon>@ function.  See the examples.
734
735 \item
736 We use the renamer!!!  Reason: we're supposed to be
737 producing @RenamedMonoBinds@ for the methods, but that means
738 producing correctly-uniquified code on the fly.  This is entirely
739 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
740 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
741 the renamer.  What a great hack!
742 \end{itemize}
743
744 \begin{code}
745 -- Generate the InstInfo for the required instance,
746 -- plus any auxiliary bindings required
747 genInst :: DFunId -> TcM (InstInfo, RenamedHsBinds)
748 genInst dfun
749   = getFixityEnv                `thenM` \ fix_env -> 
750     let
751         (tyvars,_,clas,[ty])    = tcSplitDFunTy (idType dfun)
752         clas_nm                 = className clas
753         tycon                   = tcTyConAppTyCon ty 
754         (meth_binds, aux_binds) = assoc "gen_bind:bad derived class"
755                                   gen_list (getUnique clas) fix_env tycon
756     in
757         -- Rename the auxiliary bindings (if any)
758     rnTopMonoBinds aux_binds []                 `thenM` \ (rn_aux_binds, _dus) ->
759     
760         -- Bring the right type variables into 
761         -- scope, and rename the method binds
762     bindLocalNames (map varName tyvars)         $
763     rnMethodBinds clas_nm [] meth_binds         `thenM` \ (rn_meth_binds, _fvs) ->
764
765         -- Build the InstInfo
766     returnM (InstInfo { iDFunId = dfun, iBinds = VanillaInst rn_meth_binds [] }, 
767              rn_aux_binds)
768
769 gen_list :: [(Unique, FixityEnv -> TyCon -> (RdrNameMonoBinds, RdrNameMonoBinds))]
770 gen_list = [(eqClassKey,      no_aux_binds (ignore_fix_env gen_Eq_binds))
771            ,(ordClassKey,     no_aux_binds (ignore_fix_env gen_Ord_binds))
772            ,(enumClassKey,    no_aux_binds (ignore_fix_env gen_Enum_binds))
773            ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
774            ,(ixClassKey,      no_aux_binds (ignore_fix_env gen_Ix_binds))
775            ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
776            ,(showClassKey,    no_aux_binds gen_Show_binds)
777            ,(readClassKey,    no_aux_binds gen_Read_binds)
778            ,(dataClassKey,    gen_Data_binds)
779            ]
780
781   -- no_aux_binds is used for generators that don't 
782   -- need to produce any auxiliary bindings
783 no_aux_binds f fix_env tc = (f fix_env tc, EmptyMonoBinds)
784 ignore_fix_env f fix_env tc = f tc
785 \end{code}
786
787
788 %************************************************************************
789 %*                                                                      *
790 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
791 %*                                                                      *
792 %************************************************************************
793
794
795 data Foo ... = ...
796
797 con2tag_Foo :: Foo ... -> Int#
798 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
799 maxtag_Foo  :: Int              -- ditto (NB: not unlifted)
800
801
802 We have a @con2tag@ function for a tycon if:
803 \begin{itemize}
804 \item
805 We're deriving @Eq@ and the tycon has nullary data constructors.
806
807 \item
808 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
809 (enum type only????)
810 \end{itemize}
811
812 We have a @tag2con@ function for a tycon if:
813 \begin{itemize}
814 \item
815 We're deriving @Enum@, or @Ix@ (enum type only???)
816 \end{itemize}
817
818 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
819
820 \begin{code}
821 genTaggeryBinds :: [DFunId] -> TcM RdrNameMonoBinds
822 genTaggeryBinds dfuns
823   = do  { names_so_far <- foldlM do_con2tag []           tycons_of_interest
824         ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
825         ; return (andMonoBindList (map gen_tag_n_con_monobind nm_alist_etc)) }
826   where
827     all_CTs = map simpleDFunClassTyCon dfuns
828     all_tycons              = map snd all_CTs
829     (tycons_of_interest, _) = removeDups compare all_tycons
830     
831     do_con2tag acc_Names tycon
832       | isDataTyCon tycon &&
833         ((we_are_deriving eqClassKey tycon
834             && any isNullaryDataCon (tyConDataCons tycon))
835          || (we_are_deriving ordClassKey  tycon
836             && not (isProductTyCon tycon))
837          || (we_are_deriving enumClassKey tycon)
838          || (we_are_deriving ixClassKey   tycon))
839         
840       = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
841                    : acc_Names)
842       | otherwise
843       = returnM acc_Names
844
845     do_tag2con acc_Names tycon
846       | isDataTyCon tycon &&
847          (we_are_deriving enumClassKey tycon ||
848           we_are_deriving ixClassKey   tycon
849           && isEnumerationTyCon tycon)
850       = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
851                  : (maxtag_RDR  tycon, tycon, GenMaxTag)
852                  : acc_Names)
853       | otherwise
854       = returnM acc_Names
855
856     we_are_deriving clas_key tycon
857       = is_in_eqns clas_key tycon all_CTs
858       where
859         is_in_eqns clas_key tycon [] = False
860         is_in_eqns clas_key tycon ((c,t):cts)
861           =  (clas_key == classKey c && tycon == t)
862           || is_in_eqns clas_key tycon cts
863 \end{code}
864
865 \begin{code}
866 derivingThingErr clas tys tycon tyvars why
867   = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
868          parens why]
869   where
870     pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
871
872 malformedPredErr tycon pred = ptext SLIT("Illegal deriving item") <+> ppr pred
873
874 derivCtxt :: Maybe Class -> TyCon -> SDoc
875 derivCtxt maybe_cls tycon
876   = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
877   where
878     cls = case maybe_cls of
879             Nothing -> ptext SLIT("instances")
880             Just c  -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")
881 \end{code}
882