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