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