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