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