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