Improve error message in deriving (fix Trac #2851)
[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 TcEnv
19 import TcClassDcl( tcAddDeclCtxt )      -- Small helper
20 import TcGenDeriv                       -- Deriv stuff
21 import InstEnv
22 import Inst
23 import TcHsType
24 import TcMType
25 import TcSimplify
26
27 import RnBinds
28 import RnEnv
29 import HscTypes
30
31 import Class
32 import Type
33 import ErrUtils
34 import MkId
35 import DataCon
36 import Maybes
37 import RdrName
38 import Name
39 import NameSet
40 import TyCon
41 import TcType
42 import Var
43 import VarSet
44 import PrelNames
45 import SrcLoc
46 import Util
47 import ListSetOps
48 import Outputable
49 import FastString
50 import Bag
51 \end{code}
52
53 %************************************************************************
54 %*                                                                      *
55                 Overview
56 %*                                                                      *
57 %************************************************************************
58
59 Overall plan
60 ~~~~~~~~~~~~
61 1.  Convert the decls (i.e. data/newtype deriving clauses, 
62     plus standalone deriving) to [EarlyDerivSpec]
63
64 2.  Infer the missing contexts for the Left DerivSpecs
65
66 3.  Add the derived bindings, generating InstInfos
67
68 \begin{code}
69 -- DerivSpec is purely  local to this module
70 data DerivSpec  = DS { ds_loc     :: SrcSpan 
71                      , ds_orig    :: InstOrigin 
72                      , ds_name    :: Name
73                      , ds_tvs     :: [TyVar] 
74                      , ds_theta   :: ThetaType
75                      , ds_cls     :: Class
76                      , ds_tys     :: [Type]
77                      , ds_tc      :: TyCon
78                      , ds_newtype :: Bool }
79         -- This spec implies a dfun declaration of the form
80         --       df :: forall tvs. theta => C tys
81         -- The Name is the name for the DFun we'll build
82         -- The tyvars bind all the variables in the theta
83         -- For family indexes, the tycon in 
84         --       in ds_tys is the *family* tycon
85         --       in ds_tc  is the *representation* tycon
86         -- For non-family tycons, both are the same
87
88         -- ds_newtype = True  <=> Newtype deriving
89         --              False <=> Vanilla deriving
90
91 type EarlyDerivSpec = Either DerivSpec DerivSpec
92         -- Left  ds => the context for the instance should be inferred
93         --             In this case ds_theta is the list of all the 
94         --                constraints needed, such as (Eq [a], Eq a)
95         --                The inference process is to reduce this to a 
96         --                simpler form (e.g. Eq a)
97         -- 
98         -- Right ds => the exact context for the instance is supplied 
99         --             by the programmer; it is ds_theta
100
101 pprDerivSpec :: DerivSpec -> SDoc
102 pprDerivSpec (DS { ds_loc = l, ds_name = n, ds_tvs = tvs, 
103                    ds_cls = c, ds_tys = tys, ds_theta = rhs })
104   = parens (hsep [ppr l, ppr n, ppr tvs, ppr c, ppr tys]
105             <+> equals <+> ppr rhs)
106 \end{code}
107
108
109 Inferring missing contexts 
110 ~~~~~~~~~~~~~~~~~~~~~~~~~~
111 Consider
112
113         data T a b = C1 (Foo a) (Bar b)
114                    | C2 Int (T b a)
115                    | C3 (T a a)
116                    deriving (Eq)
117
118 [NOTE: See end of these comments for what to do with 
119         data (C a, D b) => T a b = ...
120 ]
121
122 We want to come up with an instance declaration of the form
123
124         instance (Ping a, Pong b, ...) => Eq (T a b) where
125                 x == y = ...
126
127 It is pretty easy, albeit tedious, to fill in the code "...".  The
128 trick is to figure out what the context for the instance decl is,
129 namely @Ping@, @Pong@ and friends.
130
131 Let's call the context reqd for the T instance of class C at types
132 (a,b, ...)  C (T a b).  Thus:
133
134         Eq (T a b) = (Ping a, Pong b, ...)
135
136 Now we can get a (recursive) equation from the @data@ decl:
137
138         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
139                    u Eq (T b a) u Eq Int        -- From C2
140                    u Eq (T a a)                 -- From C3
141
142 Foo and Bar may have explicit instances for @Eq@, in which case we can
143 just substitute for them.  Alternatively, either or both may have
144 their @Eq@ instances given by @deriving@ clauses, in which case they
145 form part of the system of equations.
146
147 Now all we need do is simplify and solve the equations, iterating to
148 find the least fixpoint.  Notice that the order of the arguments can
149 switch around, as here in the recursive calls to T.
150
151 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
152
153 We start with:
154
155         Eq (T a b) = {}         -- The empty set
156
157 Next iteration:
158         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
159                    u Eq (T b a) u Eq Int        -- From C2
160                    u Eq (T a a)                 -- From C3
161
162         After simplification:
163                    = Eq a u Ping b u {} u {} u {}
164                    = Eq a u Ping b
165
166 Next iteration:
167
168         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
169                    u Eq (T b a) u Eq Int        -- From C2
170                    u Eq (T a a)                 -- From C3
171
172         After simplification:
173                    = Eq a u Ping b
174                    u (Eq b u Ping a)
175                    u (Eq a u Ping a)
176
177                    = Eq a u Ping b u Eq b u Ping a
178
179 The next iteration gives the same result, so this is the fixpoint.  We
180 need to make a canonical form of the RHS to ensure convergence.  We do
181 this by simplifying the RHS to a form in which
182
183         - the classes constrain only tyvars
184         - the list is sorted by tyvar (major key) and then class (minor key)
185         - no duplicates, of course
186
187 So, here are the synonyms for the ``equation'' structures:
188
189
190 Note [Data decl contexts]
191 ~~~~~~~~~~~~~~~~~~~~~~~~~
192 Consider
193
194         data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
195
196 We will need an instance decl like:
197
198         instance (Read a, RealFloat a) => Read (Complex a) where
199           ...
200
201 The RealFloat in the context is because the read method for Complex is bound
202 to construct a Complex, and doing that requires that the argument type is
203 in RealFloat. 
204
205 But this ain't true for Show, Eq, Ord, etc, since they don't construct
206 a Complex; they only take them apart.
207
208 Our approach: identify the offending classes, and add the data type
209 context to the instance decl.  The "offending classes" are
210
211         Read, Enum?
212
213 FURTHER NOTE ADDED March 2002.  In fact, Haskell98 now requires that
214 pattern matching against a constructor from a data type with a context
215 gives rise to the constraints for that context -- or at least the thinned
216 version.  So now all classes are "offending".
217
218 Note [Newtype deriving]
219 ~~~~~~~~~~~~~~~~~~~~~~~
220 Consider this:
221     class C a b
222     instance C [a] Char
223     newtype T = T Char deriving( C [a] )
224
225 Notice the free 'a' in the deriving.  We have to fill this out to 
226     newtype T = T Char deriving( forall a. C [a] )
227
228 And then translate it to:
229     instance C [a] Char => C [a] T where ...
230     
231         
232 Note [Newtype deriving superclasses]
233 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
234 (See also Trac #1220 for an interesting exchange on newtype
235 deriving and superclasses.)
236
237 The 'tys' here come from the partial application in the deriving
238 clause. The last arg is the new instance type.
239
240 We must pass the superclasses; the newtype might be an instance
241 of them in a different way than the representation type
242 E.g.            newtype Foo a = Foo a deriving( Show, Num, Eq )
243 Then the Show instance is not done via isomorphism; it shows
244         Foo 3 as "Foo 3"
245 The Num instance is derived via isomorphism, but the Show superclass
246 dictionary must the Show instance for Foo, *not* the Show dictionary
247 gotten from the Num dictionary. So we must build a whole new dictionary
248 not just use the Num one.  The instance we want is something like:
249      instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
250         (+) = ((+)@a)
251         ...etc...
252 There may be a coercion needed which we get from the tycon for the newtype
253 when the dict is constructed in TcInstDcls.tcInstDecl2
254
255
256
257
258 %************************************************************************
259 %*                                                                      *
260 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
261 %*                                                                      *
262 %************************************************************************
263
264 \begin{code}
265 tcDeriving  :: [LTyClDecl Name]  -- All type constructors
266             -> [LInstDecl Name]  -- All instance declarations
267             -> [LDerivDecl Name] -- All stand-alone deriving declarations
268             -> TcM ([InstInfo Name],    -- The generated "instance decls"
269                     HsValBinds Name)    -- Extra generated top-level bindings
270
271 tcDeriving tycl_decls inst_decls deriv_decls
272   = recoverM (return ([], emptyValBindsOut)) $
273     do  {       -- Fish the "deriving"-related information out of the TcEnv
274                 -- And make the necessary "equations".
275           is_boot <- tcIsHsBoot
276         ; traceTc (text "tcDeriving" <+> ppr is_boot)
277         ; early_specs <- makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
278
279         ; overlap_flag <- getOverlapFlag
280         ; let (infer_specs, given_specs) = splitEithers early_specs
281         ; insts1 <- mapM (genInst overlap_flag) given_specs
282
283         ; final_specs <- extendLocalInstEnv (map (iSpec . fst) insts1) $
284                          inferInstanceContexts overlap_flag infer_specs
285
286         ; insts2 <- mapM (genInst overlap_flag) final_specs
287
288                  -- Generate the generic to/from functions from each type declaration
289         ; gen_binds <- mkGenericBinds is_boot
290         ; (inst_info, rn_binds) <- renameDeriv is_boot gen_binds (insts1 ++ insts2)
291
292         ; dflags <- getDOpts
293         ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
294                  (ddump_deriving inst_info rn_binds))
295
296         ; return (inst_info, rn_binds) }
297   where
298     ddump_deriving :: [InstInfo Name] -> HsValBinds Name -> SDoc
299     ddump_deriving inst_infos extra_binds
300       = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
301
302 renameDeriv :: Bool -> LHsBinds RdrName
303             -> [(InstInfo RdrName, DerivAuxBinds)]
304             -> TcM ([InstInfo Name], HsValBinds Name)
305 renameDeriv is_boot gen_binds insts
306   | is_boot     -- If we are compiling a hs-boot file, don't generate any derived bindings
307                 -- The inst-info bindings will all be empty, but it's easier to
308                 -- just use rn_inst_info to change the type appropriately
309   = do  { rn_inst_infos <- mapM rn_inst_info inst_infos 
310         ; return (rn_inst_infos, emptyValBindsOut) }
311
312   | otherwise
313   = discardWarnings $    -- Discard warnings about unused bindings etc
314     do  { (rn_gen, dus_gen) <- setOptM Opt_ScopedTypeVariables $  -- Type signatures in patterns 
315                                                                   -- are used in the generic binds
316                                rnTopBinds (ValBindsIn gen_binds [])
317         ; keepAliveSetTc (duDefs dus_gen)       -- Mark these guys to be kept alive
318
319                 -- Generate and rename any extra not-one-inst-decl-specific binds, 
320                 -- notably "con2tag" and/or "tag2con" functions.  
321                 -- Bring those names into scope before renaming the instances themselves
322         ; loc <- getSrcSpanM    -- Generic loc for shared bindings
323         ; let aux_binds = listToBag $ map (genAuxBind loc) $ 
324                           rm_dups [] $ concat deriv_aux_binds
325         ; rn_aux_lhs <- rnTopBindsLHS emptyFsEnv (ValBindsIn aux_binds [])
326         ; let aux_names = map unLoc (collectHsValBinders rn_aux_lhs)
327
328         ; bindLocalNames aux_names $ 
329     do  { (rn_aux, _dus) <- rnTopBindsRHS (mkNameSet aux_names) rn_aux_lhs
330         ; rn_inst_infos <- mapM rn_inst_info inst_infos
331         ; return (rn_inst_infos, rn_aux `plusHsValBinds` rn_gen) } }
332
333   where
334     (inst_infos, deriv_aux_binds) = unzip insts
335     
336         -- Remove duplicate requests for auxilliary bindings
337     rm_dups acc [] = acc
338     rm_dups acc (b:bs) | any (isDupAux b) acc = rm_dups acc bs
339                        | otherwise            = rm_dups (b:acc) bs
340
341
342     rn_inst_info (InstInfo { iSpec = inst, iBinds = NewTypeDerived })
343         = return (InstInfo { iSpec = inst, iBinds = NewTypeDerived })
344
345     rn_inst_info (InstInfo { iSpec = inst, iBinds = VanillaInst binds sigs })
346         =       -- Bring the right type variables into 
347                 -- scope (yuk), and rename the method binds
348            ASSERT( null sigs )
349            bindLocalNames (map Var.varName tyvars) $
350            do { (rn_binds, _fvs) <- rnMethodBinds clas_nm (\_ -> []) [] binds
351               ; return (InstInfo { iSpec = inst, iBinds = VanillaInst rn_binds [] }) }
352         where
353           (tyvars,_,clas,_) = instanceHead inst
354           clas_nm           = className clas
355
356 -----------------------------------------
357 mkGenericBinds :: Bool -> TcM (LHsBinds RdrName)
358 mkGenericBinds is_boot
359   | is_boot 
360   = return emptyBag
361   | otherwise
362   = do  { gbl_env <- getGblEnv
363         ; let tcs = typeEnvTyCons (tcg_type_env gbl_env)
364         ; return (unionManyBags [ mkTyConGenericBinds tc | 
365                                   tc <- tcs, tyConHasGenerics tc ]) }
366                 -- We are only interested in the data type declarations,
367                 -- and then only in the ones whose 'has-generics' flag is on
368                 -- The predicate tyConHasGenerics finds both of these
369 \end{code}
370
371
372 %************************************************************************
373 %*                                                                      *
374                 From HsSyn to DerivSpec
375 %*                                                                      *
376 %************************************************************************
377
378 @makeDerivSpecs@ fishes around to find the info about needed derived instances.
379
380 \begin{code}
381 makeDerivSpecs :: Bool 
382                -> [LTyClDecl Name] 
383                -> [LInstDecl Name]
384                -> [LDerivDecl Name] 
385                -> TcM [EarlyDerivSpec]
386
387 makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
388   | is_boot     -- No 'deriving' at all in hs-boot files
389   = do  { mapM_ add_deriv_err deriv_locs 
390         ; return [] }
391   | otherwise
392   = do  { eqns1 <- mapAndRecoverM deriveTyData all_tydata
393         ; eqns2 <- mapAndRecoverM deriveStandalone deriv_decls
394         ; return (eqns1 ++ eqns2) }
395   where
396     extractTyDataPreds decls
397       = [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
398
399     all_tydata :: [(LHsType Name, LTyClDecl Name)]
400         -- Derived predicate paired with its data type declaration
401     all_tydata = extractTyDataPreds tycl_decls ++
402                  [ pd                -- Traverse assoc data families
403                  | L _ (InstDecl _ _ _ ats) <- inst_decls
404                  , pd <- extractTyDataPreds ats ]
405
406     deriv_locs = map (getLoc . snd) all_tydata
407                  ++ map getLoc deriv_decls
408
409     add_deriv_err loc = setSrcSpan loc $
410                         addErr (hang (ptext (sLit "Deriving not permitted in hs-boot file"))
411                                    2 (ptext (sLit "Use an instance declaration instead")))
412
413 ------------------------------------------------------------------
414 deriveStandalone :: LDerivDecl Name -> TcM EarlyDerivSpec
415 -- Standalone deriving declarations
416 --  e.g.   deriving instance Show a => Show (T a)
417 -- Rather like tcLocalInstDecl
418 deriveStandalone (L loc (DerivDecl deriv_ty))
419   = setSrcSpan loc                   $
420     addErrCtxt (standaloneCtxt deriv_ty)  $
421     do { traceTc (text "standalone deriving decl for" <+> ppr deriv_ty)
422        ; (tvs, theta, tau) <- tcHsInstHead deriv_ty
423        ; traceTc (text "standalone deriving;"
424               <+> text "tvs:" <+> ppr tvs
425               <+> text "theta:" <+> ppr theta
426               <+> text "tau:" <+> ppr tau)
427        ; (cls, inst_tys) <- checkValidInstHead tau
428        ; checkValidInstance tvs theta cls inst_tys
429                 -- C.f. TcInstDcls.tcLocalInstDecl1
430
431        ; let cls_tys = take (length inst_tys - 1) inst_tys
432              inst_ty = last inst_tys
433        ; traceTc (text "standalone deriving;"
434               <+> text "class:" <+> ppr cls
435               <+> text "class types:" <+> ppr cls_tys
436               <+> text "type:" <+> ppr inst_ty)
437        ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
438                    (Just theta) }
439
440 ------------------------------------------------------------------
441 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM EarlyDerivSpec
442 deriveTyData (L loc deriv_pred, L _ decl@(TyData { tcdLName = L _ tycon_name, 
443                                                    tcdTyVars = tv_names, 
444                                                    tcdTyPats = ty_pats }))
445   = setSrcSpan loc     $        -- Use the location of the 'deriving' item
446     tcAddDeclCtxt decl $
447     do  { (tvs, tc, tc_args) <- get_lhs ty_pats
448         ; tcExtendTyVarEnv tvs $        -- Deriving preds may (now) mention
449                                         -- the type variables for the type constructor
450
451     do  { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
452                 -- The "deriv_pred" is a LHsType to take account of the fact that for
453                 -- newtype deriving we allow deriving (forall a. C [a]).
454
455         -- Given data T a b c = ... deriving( C d ),
456         -- we want to drop type variables from T so that (C d (T a)) is well-kinded
457         ; let cls_tyvars = classTyVars cls
458               kind = tyVarKind (last cls_tyvars)
459               (arg_kinds, _) = splitKindFunTys kind
460               n_args_to_drop = length arg_kinds 
461               n_args_to_keep = tyConArity tc - n_args_to_drop
462               args_to_drop   = drop n_args_to_keep tc_args
463               inst_ty        = mkTyConApp tc (take n_args_to_keep tc_args)
464               inst_ty_kind   = typeKind inst_ty
465               dropped_tvs    = mkVarSet (mapCatMaybes getTyVar_maybe args_to_drop)
466               univ_tvs       = (mkVarSet tvs `extendVarSetList` deriv_tvs)
467                                         `minusVarSet` dropped_tvs
468  
469         -- Check that the result really is well-kinded
470         ; checkTc (n_args_to_keep >= 0 && (inst_ty_kind `eqKind` kind))
471                   (derivingKindErr tc cls cls_tys kind)
472
473         ; checkTc (sizeVarSet dropped_tvs == n_args_to_drop &&           -- (a)
474                    tyVarsOfTypes (inst_ty:cls_tys) `subVarSet` univ_tvs) -- (b)
475                   (derivingEtaErr cls cls_tys inst_ty)
476                 -- Check that 
477                 --  (a) The data type can be eta-reduced; eg reject:
478                 --              data instance T a a = ... deriving( Monad )
479                 --  (b) The type class args do not mention any of the dropped type
480                 --      variables 
481                 --              newtype T a s = ... deriving( ST s )
482
483         -- Type families can't be partially applied
484         -- e.g.   newtype instance T Int a = MkT [a] deriving( Monad )
485         -- Note [Deriving, type families, and partial applications]
486         ; checkTc (not (isOpenTyCon tc) || n_args_to_drop == 0)
487                   (typeFamilyPapErr tc cls cls_tys inst_ty)
488
489         ; mkEqnHelp DerivOrigin (varSetElems univ_tvs) cls cls_tys inst_ty Nothing } }
490   where
491         -- Tiresomely we must figure out the "lhs", which is awkward for type families
492         -- E.g.   data T a b = .. deriving( Eq )
493         --          Here, the lhs is (T a b)
494         --        data instance TF Int b = ... deriving( Eq )
495         --          Here, the lhs is (TF Int b)
496         -- But if we just look up the tycon_name, we get is the *family*
497         -- tycon, but not pattern types -- they are in the *rep* tycon.
498     get_lhs Nothing     = do { tc <- tcLookupTyCon tycon_name
499                              ; let tvs = tyConTyVars tc
500                              ; return (tvs, tc, mkTyVarTys tvs) }
501     get_lhs (Just pats) = do { let hs_app = nlHsTyConApp tycon_name pats
502                              ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
503                              ; let (tc, tc_args) = tcSplitTyConApp tc_app
504                              ; return (tvs, tc, tc_args) }
505
506 deriveTyData _other
507   = panic "derivTyData" -- Caller ensures that only TyData can happen
508 \end{code}
509
510 Note [Deriving, type families, and partial applications]
511 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
512 When there are no type families, it's quite easy:
513
514     newtype S a = MkS [a]
515     -- :CoS :: S  ~ []  -- Eta-reduced
516
517     instance Eq [a] => Eq (S a)         -- by coercion sym (Eq (coMkS a)) : Eq [a] ~ Eq (S a)
518     instance Monad [] => Monad S        -- by coercion sym (Monad coMkS)  : Monad [] ~ Monad S 
519
520 When type familes are involved it's trickier:
521
522     data family T a b
523     newtype instance T Int a = MkT [a] deriving( Eq, Monad )
524     -- :RT is the representation type for (T Int a)
525     --  :CoF:R1T a :: T Int a ~ :RT a   -- Not eta reduced
526     --  :Co:R1T    :: :RT ~ []          -- Eta-reduced
527
528     instance Eq [a] => Eq (T Int a)     -- easy by coercion
529     instance Monad [] => Monad (T Int)  -- only if we can eta reduce???
530
531 The "???" bit is that we don't build the :CoF thing in eta-reduced form
532 Henc the current typeFamilyPapErr, even though the instance makes sense.
533 After all, we can write it out
534     instance Monad [] => Monad (T Int)  -- only if we can eta reduce???
535       return x = MkT [x]
536       ... etc ...       
537
538 \begin{code}
539 mkEqnHelp :: InstOrigin -> [TyVar] -> Class -> [Type] -> Type
540           -> Maybe ThetaType    -- Just    => context supplied (standalone deriving)
541                                 -- Nothing => context inferred (deriving on data decl)
542           -> TcRn EarlyDerivSpec
543 -- Make the EarlyDerivSpec for an instance
544 --      forall tvs. theta => cls (tys ++ [ty])
545 -- where the 'theta' is optional (that's the Maybe part)
546 -- Assumes that this declaration is well-kinded
547
548 mkEqnHelp orig tvs cls cls_tys tc_app mtheta
549   | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
550   , isAlgTyCon tycon    -- Check for functions, primitive types etc
551   = do  { (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon tc_args
552                   -- Be careful to test rep_tc here: in the case of families, 
553                   -- we want to check the instance tycon, not the family tycon
554
555         -- For standalone deriving (mtheta /= Nothing), 
556         -- check that all the data constructors are in scope.
557         -- No need for this when deriving Typeable, becuase we don't need
558         -- the constructors for that.
559         ; rdr_env <- getGlobalRdrEnv
560         ; let hidden_data_cons = isAbstractTyCon rep_tc || any not_in_scope (tyConDataCons rep_tc)
561               not_in_scope dc  = null (lookupGRE_Name rdr_env (dataConName dc))
562         ; checkTc (isNothing mtheta || 
563                    not hidden_data_cons ||
564                    className cls `elem` typeableClassNames) 
565                   (derivingHiddenErr tycon)
566
567         ; mayDeriveDataTypeable <- doptM Opt_DeriveDataTypeable
568         ; newtype_deriving <- doptM Opt_GeneralizedNewtypeDeriving
569
570         ; if isDataTyCon rep_tc then
571                 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys 
572                               tycon tc_args rep_tc rep_tc_args mtheta
573           else
574                 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving
575                              tvs cls cls_tys 
576                              tycon tc_args rep_tc rep_tc_args mtheta }
577   | otherwise
578   = failWithTc (derivingThingErr cls cls_tys tc_app
579                (ptext (sLit "The last argument of the instance must be a data or newtype application")))
580 \end{code}
581
582 Note [Looking up family instances for deriving]
583 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
584 tcLookupFamInstExact is an auxiliary lookup wrapper which requires
585 that looked-up family instances exist.  If called with a vanilla
586 tycon, the old type application is simply returned.
587
588 If we have
589   data instance F () = ... deriving Eq
590   data instance F () = ... deriving Eq
591 then tcLookupFamInstExact will be confused by the two matches;
592 but that can't happen because tcInstDecls1 doesn't call tcDeriving
593 if there are any overlaps.
594
595 There are two other things that might go wrong with the lookup.
596 First, we might see a standalone deriving clause
597         deriving Eq (F ())
598 when there is no data instance F () in scope. 
599
600 Note that it's OK to have
601   data instance F [a] = ...
602   deriving Eq (F [(a,b)])
603 where the match is not exact; the same holds for ordinary data types
604 with standalone deriving declrations.
605
606 \begin{code}
607 tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
608 tcLookupFamInstExact tycon tys
609   | not (isOpenTyCon tycon)
610   = return (tycon, tys)
611   | otherwise
612   = do { maybeFamInst <- tcLookupFamInst tycon tys
613        ; case maybeFamInst of
614            Nothing      -> famInstNotFound tycon tys
615            Just famInst -> return famInst
616        }
617
618 famInstNotFound :: TyCon -> [Type] -> TcM a
619 famInstNotFound tycon tys 
620   = failWithTc (ptext (sLit "No family instance for")
621                         <+> quotes (pprTypeApp tycon tys))
622 \end{code}
623
624
625 %************************************************************************
626 %*                                                                      *
627                 Deriving data types
628 %*                                                                      *
629 %************************************************************************
630
631 \begin{code}
632 mkDataTypeEqn :: InstOrigin -> Bool -> [Var] -> Class -> [Type]
633               -> TyCon -> [Type] -> TyCon -> [Type] -> Maybe ThetaType
634               -> TcRn EarlyDerivSpec    -- Return 'Nothing' if error
635                 
636 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
637               tycon tc_args rep_tc rep_tc_args mtheta
638   = case checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc of
639         -- NB: pass the *representation* tycon to checkSideConditions
640         CanDerive -> mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
641         NonDerivableClass       -> bale_out (nonStdErr cls)
642         DerivableClassError msg -> bale_out msg
643   where
644     bale_out msg = failWithTc (derivingThingErr cls cls_tys (mkTyConApp tycon tc_args) msg)
645
646 mk_data_eqn, mk_typeable_eqn
647    :: InstOrigin -> [TyVar] -> Class 
648    -> TyCon -> [TcType] -> TyCon -> [TcType] -> Maybe ThetaType
649    -> TcM EarlyDerivSpec
650 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
651   | getName cls `elem` typeableClassNames
652   = mk_typeable_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
653
654   | otherwise
655   = do  { dfun_name <- new_dfun_name cls tycon
656         ; loc <- getSrcSpanM
657         ; let ordinary_constraints
658                 = [ mkClassPred cls [arg_ty] 
659                   | data_con <- tyConDataCons rep_tc,
660                     arg_ty   <- ASSERT( isVanillaDataCon data_con )
661                                 dataConInstOrigArgTys data_con rep_tc_args,
662                     not (isUnLiftedType arg_ty) ]
663                         -- No constraints for unlifted types
664                         -- Where they are legal we generate specilised function calls
665
666                         -- See Note [Superclasses of derived instance]
667               sc_constraints = substTheta (zipOpenTvSubst (classTyVars cls) inst_tys)
668                                           (classSCTheta cls)
669               inst_tys = [mkTyConApp tycon tc_args]
670
671               stupid_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
672               stupid_constraints = substTheta stupid_subst (tyConStupidTheta rep_tc)
673               all_constraints = stupid_constraints ++ sc_constraints ++ ordinary_constraints
674
675               spec = DS { ds_loc = loc, ds_orig = orig
676                         , ds_name = dfun_name, ds_tvs = tvs 
677                         , ds_cls = cls, ds_tys = inst_tys, ds_tc = rep_tc
678                         , ds_theta =  mtheta `orElse` all_constraints
679                         , ds_newtype = False }
680
681         ; return (if isJust mtheta then Right spec      -- Specified context
682                                    else Left spec) }    -- Infer context
683
684 mk_typeable_eqn orig tvs cls tycon tc_args rep_tc _rep_tc_args mtheta
685         -- The Typeable class is special in several ways
686         --        data T a b = ... deriving( Typeable )
687         -- gives
688         --        instance Typeable2 T where ...
689         -- Notice that:
690         -- 1. There are no constraints in the instance
691         -- 2. There are no type variables either
692         -- 3. The actual class we want to generate isn't necessarily
693         --      Typeable; it depends on the arity of the type
694   | isNothing mtheta    -- deriving on a data type decl
695   = do  { checkTc (cls `hasKey` typeableClassKey)
696                   (ptext (sLit "Use deriving( Typeable ) on a data type declaration"))
697         ; real_cls <- tcLookupClass (typeableClassNames !! tyConArity tycon)
698         ; mk_typeable_eqn orig tvs real_cls tycon [] rep_tc [] (Just []) }
699
700   | otherwise           -- standaone deriving
701   = do  { checkTc (null tc_args)
702                   (ptext (sLit "Derived typeable instance must be of form (Typeable") 
703                         <> int (tyConArity tycon) <+> ppr tycon <> rparen)
704         ; dfun_name <- new_dfun_name cls tycon
705         ; loc <- getSrcSpanM
706         ; return (Right $
707                   DS { ds_loc = loc, ds_orig = orig, ds_name = dfun_name, ds_tvs = []
708                      , ds_cls = cls, ds_tys = [mkTyConApp tycon []], ds_tc = rep_tc
709                      , ds_theta = mtheta `orElse` [], ds_newtype = False })  }
710
711 ------------------------------------------------------------------
712 -- Check side conditions that dis-allow derivability for particular classes
713 -- This is *apart* from the newtype-deriving mechanism
714 --
715 -- Here we get the representation tycon in case of family instances as it has
716 -- the data constructors - but we need to be careful to fall back to the
717 -- family tycon (with indexes) in error messages.
718
719 data DerivStatus = CanDerive
720                  | DerivableClassError SDoc     -- Standard class, but can't do it
721                  | NonDerivableClass            -- Non-standard class
722
723 checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> DerivStatus
724 checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
725   | Just cond <- sideConditions cls
726   = case (cond (mayDeriveDataTypeable, rep_tc)) of
727         Just err -> DerivableClassError err     -- Class-specific error
728         Nothing  | null cls_tys -> CanDerive
729                  | otherwise    -> DerivableClassError ty_args_why      -- e.g. deriving( Eq s )
730   | otherwise = NonDerivableClass       -- Not a standard class
731   where
732     ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "is not a class")
733
734 nonStdErr :: Class -> SDoc
735 nonStdErr cls = quotes (ppr cls) <+> ptext (sLit "is not a derivable class")
736
737 sideConditions :: Class -> Maybe Condition
738 sideConditions cls
739   | cls_key == eqClassKey      = Just cond_std
740   | cls_key == ordClassKey     = Just cond_std
741   | cls_key == showClassKey    = Just cond_std
742   | cls_key == readClassKey    = Just (cond_std `andCond` cond_noUnliftedArgs)
743   | cls_key == enumClassKey    = Just (cond_std `andCond` cond_isEnumeration)
744   | cls_key == ixClassKey      = Just (cond_std `andCond` cond_enumOrProduct)
745   | cls_key == boundedClassKey = Just (cond_std `andCond` cond_enumOrProduct)
746   | cls_key == dataClassKey    = Just (cond_mayDeriveDataTypeable `andCond` cond_std `andCond` cond_noUnliftedArgs)
747   | getName cls `elem` typeableClassNames = Just (cond_mayDeriveDataTypeable `andCond` cond_typeableOK)
748   | otherwise = Nothing
749   where
750     cls_key = getUnique cls
751
752 type Condition = (Bool, TyCon) -> Maybe SDoc
753         -- Bool is whether or not we are allowed to derive Data and Typeable
754         -- TyCon is the *representation* tycon if the 
755         --      data type is an indexed one
756         -- Nothing => OK
757
758 orCond :: Condition -> Condition -> Condition
759 orCond c1 c2 tc 
760   = case c1 tc of
761         Nothing -> Nothing              -- c1 succeeds
762         Just x  -> case c2 tc of        -- c1 fails
763                      Nothing -> Nothing
764                      Just y  -> Just (x $$ ptext (sLit "  and") $$ y)
765                                         -- Both fail
766
767 andCond :: Condition -> Condition -> Condition
768 andCond c1 c2 tc = case c1 tc of
769                      Nothing -> c2 tc   -- c1 succeeds
770                      Just x  -> Just x  -- c1 fails
771
772 cond_std :: Condition
773 cond_std (_, rep_tc)
774   | any (not . isVanillaDataCon) data_cons = Just existential_why     
775   | null data_cons                         = Just no_cons_why
776   | otherwise                              = Nothing
777   where
778     data_cons       = tyConDataCons rep_tc
779     no_cons_why     = quotes (pprSourceTyCon rep_tc) <+> 
780                       ptext (sLit "has no data constructors")
781     existential_why = quotes (pprSourceTyCon rep_tc) <+> 
782                       ptext (sLit "has non-Haskell-98 constructor(s)")
783   
784 cond_enumOrProduct :: Condition
785 cond_enumOrProduct = cond_isEnumeration `orCond` 
786                        (cond_isProduct `andCond` cond_noUnliftedArgs)
787
788 cond_noUnliftedArgs :: Condition
789 -- For some classes (eg Eq, Ord) we allow unlifted arg types
790 -- by generating specilaised code.  For others (eg Data) we don't.
791 cond_noUnliftedArgs (_, tc)
792   | null bad_cons = Nothing
793   | otherwise     = Just why
794   where
795     bad_cons = [ con | con <- tyConDataCons tc
796                      , any isUnLiftedType (dataConOrigArgTys con) ]
797     why = ptext (sLit "Constructor") <+> quotes (ppr (head bad_cons))
798           <+> ptext (sLit "has arguments of unlifted type")
799
800 cond_isEnumeration :: Condition
801 cond_isEnumeration (_, rep_tc)
802   | isEnumerationTyCon rep_tc = Nothing
803   | otherwise                 = Just why
804   where
805     why = quotes (pprSourceTyCon rep_tc) <+> 
806           ptext (sLit "has non-nullary constructors")
807
808 cond_isProduct :: Condition
809 cond_isProduct (_, rep_tc)
810   | isProductTyCon rep_tc = Nothing
811   | otherwise             = Just why
812   where
813     why = quotes (pprSourceTyCon rep_tc) <+> 
814           ptext (sLit "has more than one constructor")
815
816 cond_typeableOK :: Condition
817 -- OK for Typeable class
818 -- Currently: (a) args all of kind *
819 --            (b) 7 or fewer args
820 cond_typeableOK (_, rep_tc)
821   | tyConArity rep_tc > 7       = Just too_many
822   | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc)) 
823                                 = Just bad_kind
824   | isFamInstTyCon rep_tc       = Just fam_inst  -- no Typable for family insts
825   | otherwise                   = Nothing
826   where
827     too_many = quotes (pprSourceTyCon rep_tc) <+> 
828                ptext (sLit "has too many arguments")
829     bad_kind = quotes (pprSourceTyCon rep_tc) <+> 
830                ptext (sLit "has arguments of kind other than `*'")
831     fam_inst = quotes (pprSourceTyCon rep_tc) <+> 
832                ptext (sLit "is a type family")
833
834 cond_mayDeriveDataTypeable :: Condition
835 cond_mayDeriveDataTypeable (mayDeriveDataTypeable, _)
836  | mayDeriveDataTypeable = Nothing
837  | otherwise = Just why
838   where
839     why  = ptext (sLit "You need -XDeriveDataTypeable to derive an instance for this class")
840
841 std_class_via_iso :: Class -> Bool
842 std_class_via_iso clas  -- These standard classes can be derived for a newtype
843                         -- using the isomorphism trick *even if no -fglasgow-exts*
844   = classKey clas `elem`  [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
845         -- Not Read/Show because they respect the type
846         -- Not Enum, because newtypes are never in Enum
847
848
849 new_dfun_name :: Class -> TyCon -> TcM Name
850 new_dfun_name clas tycon        -- Just a simple wrapper
851   = do { loc <- getSrcSpanM     -- The location of the instance decl, not of the tycon
852         ; newDFunName clas [mkTyConApp tycon []] loc }
853         -- The type passed to newDFunName is only used to generate
854         -- a suitable string; hence the empty type arg list
855 \end{code}
856
857 Note [Superclasses of derived instance] 
858 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
859 In general, a derived instance decl needs the superclasses of the derived
860 class too.  So if we have
861         data T a = ...deriving( Ord )
862 then the initial context for Ord (T a) should include Eq (T a).  Often this is 
863 redundant; we'll also generate an Ord constraint for each constructor argument,
864 and that will probably generate enough constraints to make the Eq (T a) constraint 
865 be satisfied too.  But not always; consider:
866
867  data S a = S
868  instance Eq (S a)
869  instance Ord (S a)
870
871  data T a = MkT (S a) deriving( Ord )
872  instance Num a => Eq (T a)
873
874 The derived instance for (Ord (T a)) must have a (Num a) constraint!
875 Similarly consider:
876         data T a = MkT deriving( Data, Typeable )
877 Here there *is* no argument field, but we must nevertheless generate
878 a context for the Data instances:
879         instance Typable a => Data (T a) where ...
880
881
882 %************************************************************************
883 %*                                                                      *
884                 Deriving newtypes
885 %*                                                                      *
886 %************************************************************************
887
888 \begin{code}
889 mkNewTypeEqn :: InstOrigin -> Bool -> Bool -> [Var] -> Class
890              -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
891              -> Maybe ThetaType
892              -> TcRn EarlyDerivSpec
893 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving tvs
894              cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
895 -- Want: instance (...) => cls (cls_tys ++ [tycon tc_args]) where ...
896   | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
897   = do  { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
898         ; dfun_name <- new_dfun_name cls tycon
899         ; loc <- getSrcSpanM
900         ; let spec = DS { ds_loc = loc, ds_orig = orig
901                         , ds_name = dfun_name, ds_tvs = varSetElems dfun_tvs 
902                         , ds_cls = cls, ds_tys = inst_tys, ds_tc = rep_tycon
903                         , ds_theta =  mtheta `orElse` all_preds
904                         , ds_newtype = True }
905         ; return (if isJust mtheta then Right spec
906                                    else Left spec) }
907
908   | otherwise
909   = case check_conditions of
910       CanDerive -> mk_data_eqn orig tvs cls tycon tc_args rep_tycon rep_tc_args mtheta
911                                 -- Use the standard H98 method
912       DerivableClassError msg -> bale_out msg              -- Error with standard class
913       NonDerivableClass         -- Must use newtype deriving
914         | newtype_deriving    -> bale_out cant_derive_err  -- Too hard, even with newtype deriving
915         | otherwise           -> bale_out non_std_err      -- Try newtype deriving!
916   where
917         check_conditions = checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tycon
918         bale_out msg = failWithTc (derivingThingErr cls cls_tys inst_ty msg)
919
920         non_std_err = nonStdErr cls $$
921                       ptext (sLit "Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")
922
923         -- Here is the plan for newtype derivings.  We see
924         --        newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
925         -- where t is a type,
926         --       ak+1...an is a suffix of a1..an, and are all tyars
927         --       ak+1...an do not occur free in t, nor in the s1..sm
928         --       (C s1 ... sm) is a  *partial applications* of class C 
929         --                      with the last parameter missing
930         --       (T a1 .. ak) matches the kind of C's last argument
931         --              (and hence so does t)
932         -- The latter kind-check has been done by deriveTyData already,
933         -- and tc_args are already trimmed
934         --
935         -- We generate the instance
936         --       instance forall ({a1..ak} u fvs(s1..sm)).
937         --                C s1 .. sm t => C s1 .. sm (T a1...ak)
938         -- where T a1...ap is the partial application of 
939         --       the LHS of the correct kind and p >= k
940         --
941         --      NB: the variables below are:
942         --              tc_tvs = [a1, ..., an]
943         --              tyvars_to_keep = [a1, ..., ak]
944         --              rep_ty = t ak .. an
945         --              deriv_tvs = fvs(s1..sm) \ tc_tvs
946         --              tys = [s1, ..., sm]
947         --              rep_fn' = t
948         --
949         -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
950         -- We generate the instance
951         --      instance Monad (ST s) => Monad (T s) where 
952
953         nt_eta_arity = length (fst (newTyConEtadRhs rep_tycon))
954                 -- For newtype T a b = MkT (S a a b), the TyCon machinery already
955                 -- eta-reduces the represenation type, so we know that
956                 --      T a ~ S a a
957                 -- That's convenient here, because we may have to apply
958                 -- it to fewer than its original complement of arguments
959
960         -- Note [Newtype representation]
961         -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
962         -- Need newTyConRhs (*not* a recursive representation finder) 
963         -- to get the representation type. For example
964         --      newtype B = MkB Int
965         --      newtype A = MkA B deriving( Num )
966         -- We want the Num instance of B, *not* the Num instance of Int,
967         -- when making the Num instance of A!
968         rep_inst_ty = newTyConInstRhs rep_tycon rep_tc_args
969         rep_tys     = cls_tys ++ [rep_inst_ty]
970         rep_pred    = mkClassPred cls rep_tys
971                 -- rep_pred is the representation dictionary, from where
972                 -- we are gong to get all the methods for the newtype
973                 -- dictionary 
974
975
976     -- Next we figure out what superclass dictionaries to use
977     -- See Note [Newtype deriving superclasses] above
978
979         cls_tyvars = classTyVars cls
980         dfun_tvs = tyVarsOfTypes inst_tys
981         inst_ty = mkTyConApp tycon tc_args
982         inst_tys = cls_tys ++ [inst_ty]
983         sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
984                               (classSCTheta cls)
985
986                 -- If there are no tyvars, there's no need
987                 -- to abstract over the dictionaries we need
988                 -- Example:     newtype T = MkT Int deriving( C )
989                 -- We get the derived instance
990                 --              instance C T
991                 -- rather than
992                 --              instance C Int => C T
993         all_preds = rep_pred : sc_theta         -- NB: rep_pred comes first
994
995         -------------------------------------------------------------------
996         --  Figuring out whether we can only do this newtype-deriving thing
997
998         right_arity = length cls_tys + 1 == classArity cls
999
1000                 -- Never derive Read,Show,Typeable,Data this way 
1001         non_iso_class cls = className cls `elem` ([readClassName, showClassName, dataClassName] ++
1002                                                   typeableClassNames)
1003         can_derive_via_isomorphism
1004            =  not (non_iso_class cls)
1005            && right_arity                       -- Well kinded;
1006                                                 -- eg not: newtype T ... deriving( ST )
1007                                                 --      because ST needs *2* type params
1008            && eta_ok                            -- Eta reduction works
1009            && not (isRecursiveTyCon tycon)      -- Does not work for recursive tycons:
1010                                                 --      newtype A = MkA [A]
1011                                                 -- Don't want
1012                                                 --      instance Eq [A] => Eq A !!
1013                         -- Here's a recursive newtype that's actually OK
1014                         --      newtype S1 = S1 [T1 ()]
1015                         --      newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
1016                         -- It's currently rejected.  Oh well.
1017                         -- In fact we generate an instance decl that has method of form
1018                         --      meth @ instTy = meth @ repTy
1019                         -- (no coerce's).  We'd need a coerce if we wanted to handle
1020                         -- recursive newtypes too
1021
1022         -- Check that eta reduction is OK
1023         eta_ok = nt_eta_arity <= length rep_tc_args
1024                 -- The newtype can be eta-reduced to match the number
1025                 --     of type argument actually supplied
1026                 --        newtype T a b = MkT (S [a] b) deriving( Monad )
1027                 --     Here the 'b' must be the same in the rep type (S [a] b)
1028                 --     And the [a] must not mention 'b'.  That's all handled
1029                 --     by nt_eta_rity.
1030
1031         cant_derive_err = vcat [ptext (sLit "even with cunning newtype deriving:"),
1032                                 if isRecursiveTyCon tycon then
1033                                   ptext (sLit "the newtype may be recursive")
1034                                 else empty,
1035                                 if not right_arity then 
1036                                   quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "does not have arity 1")
1037                                 else empty,
1038                                 if not eta_ok then 
1039                                   ptext (sLit "cannot eta-reduce the representation type enough")
1040                                 else empty
1041                                 ]
1042 \end{code}
1043
1044
1045 %************************************************************************
1046 %*                                                                      *
1047 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
1048 %*                                                                      *
1049 %************************************************************************
1050
1051 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
1052 terms, which is the final correct RHS for the corresponding original
1053 equation.
1054 \begin{itemize}
1055 \item
1056 Each (k,TyVarTy tv) in a solution constrains only a type
1057 variable, tv.
1058
1059 \item
1060 The (k,TyVarTy tv) pairs in a solution are canonically
1061 ordered by sorting on type varible, tv, (major key) and then class, k,
1062 (minor key)
1063 \end{itemize}
1064
1065 \begin{code}
1066 inferInstanceContexts :: OverlapFlag -> [DerivSpec] -> TcM [DerivSpec]
1067
1068 inferInstanceContexts _ [] = return []
1069
1070 inferInstanceContexts oflag infer_specs
1071   = do  { traceTc (text "inferInstanceContexts" <+> vcat (map pprDerivSpec infer_specs))
1072         ; iterate_deriv 1 initial_solutions }
1073   where
1074     ------------------------------------------------------------------
1075         -- The initial solutions for the equations claim that each
1076         -- instance has an empty context; this solution is certainly
1077         -- in canonical form.
1078     initial_solutions :: [ThetaType]
1079     initial_solutions = [ [] | _ <- infer_specs ]
1080
1081     ------------------------------------------------------------------
1082         -- iterate_deriv calculates the next batch of solutions,
1083         -- compares it with the current one; finishes if they are the
1084         -- same, otherwise recurses with the new solutions.
1085         -- It fails if any iteration fails
1086     iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec]
1087     iterate_deriv n current_solns
1088       | n > 20  -- Looks as if we are in an infinite loop
1089                 -- This can happen if we have -XUndecidableInstances
1090                 -- (See TcSimplify.tcSimplifyDeriv.)
1091       = pprPanic "solveDerivEqns: probable loop" 
1092                  (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
1093       | otherwise
1094       = do {      -- Extend the inst info from the explicit instance decls
1095                   -- with the current set of solutions, and simplify each RHS
1096              let inst_specs = zipWithEqual "add_solns" (mkInstance2 oflag)
1097                                            current_solns infer_specs
1098            ; new_solns <- checkNoErrs $
1099                           extendLocalInstEnv inst_specs $
1100                           mapM gen_soln infer_specs
1101
1102            ; if (current_solns == new_solns) then
1103                 return [ spec { ds_theta = soln } 
1104                        | (spec, soln) <- zip infer_specs current_solns ]
1105              else
1106                 iterate_deriv (n+1) new_solns }
1107
1108     ------------------------------------------------------------------
1109     gen_soln :: DerivSpec  -> TcM [PredType]
1110     gen_soln (DS { ds_loc = loc, ds_orig = orig, ds_tvs = tyvars 
1111                  , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
1112       = setSrcSpan loc  $
1113         addErrCtxt (derivInstCtxt clas inst_tys) $ 
1114         do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
1115                 -- checkValidInstance tyvars theta clas inst_tys
1116                 -- Not necessary; see Note [Exotic derived instance contexts]
1117                 --                in TcSimplify
1118
1119                   -- Check for a bizarre corner case, when the derived instance decl should
1120                   -- have form  instance C a b => D (T a) where ...
1121                   -- Note that 'b' isn't a parameter of T.  This gives rise to all sorts
1122                   -- of problems; in particular, it's hard to compare solutions for
1123                   -- equality when finding the fixpoint.  So I just rule it out for now.
1124            ; let tv_set = mkVarSet tyvars
1125                  weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]  
1126            ; mapM_ (addErrTc . badDerivedPred) weird_preds      
1127
1128                 -- Claim: the result instance declaration is guaranteed valid
1129                 -- Hence no need to call:
1130                 --   checkValidInstance tyvars theta clas inst_tys
1131            ; return (sortLe (<=) theta) }       -- Canonicalise before returning the solution
1132
1133 ------------------------------------------------------------------
1134 mkInstance1 :: OverlapFlag -> DerivSpec -> Instance
1135 mkInstance1 overlap_flag spec = mkInstance2 overlap_flag (ds_theta spec) spec
1136
1137 mkInstance2 :: OverlapFlag -> ThetaType -> DerivSpec -> Instance
1138 mkInstance2 overlap_flag theta
1139             (DS { ds_name = dfun_name
1140                 , ds_tvs = tyvars, ds_cls = clas, ds_tys = tys })
1141   = mkLocalInstance dfun overlap_flag
1142   where
1143     dfun = mkDictFunId dfun_name tyvars theta clas tys
1144
1145
1146 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
1147 -- Add new locally-defined instances; don't bother to check
1148 -- for functional dependency errors -- that'll happen in TcInstDcls
1149 extendLocalInstEnv dfuns thing_inside
1150  = do { env <- getGblEnv
1151       ; let  inst_env' = extendInstEnvList (tcg_inst_env env) dfuns 
1152              env'      = env { tcg_inst_env = inst_env' }
1153       ; setGblEnv env' thing_inside }
1154 \end{code}
1155
1156
1157 %************************************************************************
1158 %*                                                                      *
1159 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
1160 %*                                                                      *
1161 %************************************************************************
1162
1163 After all the trouble to figure out the required context for the
1164 derived instance declarations, all that's left is to chug along to
1165 produce them.  They will then be shoved into @tcInstDecls2@, which
1166 will do all its usual business.
1167
1168 There are lots of possibilities for code to generate.  Here are
1169 various general remarks.
1170
1171 PRINCIPLES:
1172 \begin{itemize}
1173 \item
1174 We want derived instances of @Eq@ and @Ord@ (both v common) to be
1175 ``you-couldn't-do-better-by-hand'' efficient.
1176
1177 \item
1178 Deriving @Show@---also pretty common--- should also be reasonable good code.
1179
1180 \item
1181 Deriving for the other classes isn't that common or that big a deal.
1182 \end{itemize}
1183
1184 PRAGMATICS:
1185
1186 \begin{itemize}
1187 \item
1188 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
1189
1190 \item
1191 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
1192
1193 \item
1194 We {\em normally} generate code only for the non-defaulted methods;
1195 there are some exceptions for @Eq@ and (especially) @Ord@...
1196
1197 \item
1198 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
1199 constructor's numeric (@Int#@) tag.  These are generated by
1200 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
1201 these is around is given by @hasCon2TagFun@.
1202
1203 The examples under the different sections below will make this
1204 clearer.
1205
1206 \item
1207 Much less often (really just for deriving @Ix@), we use a
1208 @_tag2con_<tycon>@ function.  See the examples.
1209
1210 \item
1211 We use the renamer!!!  Reason: we're supposed to be
1212 producing @LHsBinds Name@ for the methods, but that means
1213 producing correctly-uniquified code on the fly.  This is entirely
1214 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
1215 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
1216 the renamer.  What a great hack!
1217 \end{itemize}
1218
1219 \begin{code}
1220 -- Generate the InstInfo for the required instance paired with the
1221 --   *representation* tycon for that instance,
1222 -- plus any auxiliary bindings required
1223 --
1224 -- Representation tycons differ from the tycon in the instance signature in
1225 -- case of instances for indexed families.
1226 --
1227 genInst :: OverlapFlag -> DerivSpec -> TcM (InstInfo RdrName, DerivAuxBinds)
1228 genInst oflag spec
1229   | ds_newtype spec
1230   = return (InstInfo { iSpec  = mkInstance1 oflag spec 
1231                      , iBinds = NewTypeDerived }, [])
1232
1233   | otherwise
1234   = do  { let loc        = getSrcSpan (ds_name spec)
1235               inst       = mkInstance1 oflag spec
1236               clas       = ds_cls spec
1237               rep_tycon  = ds_tc spec
1238
1239           -- In case of a family instance, we need to use the representation
1240           -- tycon (after all, it has the data constructors)
1241         ; fix_env <- getFixityEnv
1242         ; let (meth_binds, aux_binds) = genDerivBinds loc fix_env clas rep_tycon
1243
1244         -- Build the InstInfo
1245         ; return (InstInfo { iSpec = inst, 
1246                              iBinds = VanillaInst meth_binds [] },
1247                   aux_binds)
1248         }
1249
1250 genDerivBinds :: SrcSpan -> FixityEnv -> Class -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1251 genDerivBinds loc fix_env clas tycon
1252   | className clas `elem` typeableClassNames
1253   = (gen_Typeable_binds loc tycon, [])
1254
1255   | otherwise
1256   = case assocMaybe gen_list (getUnique clas) of
1257         Just gen_fn -> gen_fn loc tycon
1258         Nothing     -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1259   where
1260     gen_list :: [(Unique, SrcSpan -> TyCon -> (LHsBinds RdrName, DerivAuxBinds))]
1261     gen_list = [(eqClassKey,       gen_Eq_binds)
1262                ,(ordClassKey,      gen_Ord_binds)
1263                ,(enumClassKey,     gen_Enum_binds)
1264                ,(boundedClassKey,  gen_Bounded_binds)
1265                ,(ixClassKey,       gen_Ix_binds)
1266                ,(showClassKey,     gen_Show_binds fix_env)
1267                ,(readClassKey,     gen_Read_binds fix_env)
1268                ,(dataClassKey,     gen_Data_binds)
1269                ]
1270 \end{code}
1271
1272
1273 %************************************************************************
1274 %*                                                                      *
1275 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1276 %*                                                                      *
1277 %************************************************************************
1278
1279 \begin{code}
1280 derivingKindErr :: TyCon -> Class -> [Type] -> Kind -> Message
1281 derivingKindErr tc cls cls_tys cls_kind
1282   = hang (ptext (sLit "Cannot derive well-kinded instance of form")
1283                 <+> quotes (pprClassPred cls cls_tys <+> parens (ppr tc <+> ptext (sLit "..."))))
1284        2 (ptext (sLit "Class") <+> quotes (ppr cls)
1285             <+> ptext (sLit "expects an argument of kind") <+> quotes (pprKind cls_kind))
1286
1287 derivingEtaErr :: Class -> [Type] -> Type -> Message
1288 derivingEtaErr cls cls_tys inst_ty
1289   = sep [ptext (sLit "Cannot eta-reduce to an instance of form"),
1290          nest 2 (ptext (sLit "instance (...) =>")
1291                 <+> pprClassPred cls (cls_tys ++ [inst_ty]))]
1292
1293 typeFamilyPapErr :: TyCon -> Class -> [Type] -> Type -> Message
1294 typeFamilyPapErr tc cls cls_tys inst_ty
1295   = hang (ptext (sLit "Derived instance") <+> quotes (pprClassPred cls (cls_tys ++ [inst_ty])))
1296        2 (ptext (sLit "requires illegal partial application of data type family") <+> ppr tc) 
1297
1298 derivingThingErr :: Class -> [Type] -> Type -> Message -> Message
1299 derivingThingErr clas tys ty why
1300   = sep [hsep [ptext (sLit "Can't make a derived instance of"), 
1301                quotes (ppr pred)],
1302          nest 2 (parens why)]
1303   where
1304     pred = mkClassPred clas (tys ++ [ty])
1305
1306 derivingHiddenErr :: TyCon -> SDoc
1307 derivingHiddenErr tc
1308   = hang (ptext (sLit "The data constructors of") <+> quotes (ppr tc) <+> ptext (sLit "are not all in scope"))
1309        2 (ptext (sLit "so you cannot derive an instance for it"))
1310
1311 standaloneCtxt :: LHsType Name -> SDoc
1312 standaloneCtxt ty = hang (ptext (sLit "In the stand-alone deriving instance for")) 
1313                        2 (quotes (ppr ty))
1314
1315 derivInstCtxt :: Class -> [Type] -> Message
1316 derivInstCtxt clas inst_tys
1317   = vcat [ptext (sLit "Alternative fix: use a standalone 'deriving instance' declaration"),
1318           nest 2 (ptext (sLit "instead, so you can specify the instance context yourself")),
1319           ptext (sLit "When deriving the instance for") <+> parens (pprClassPred clas inst_tys)]
1320
1321 badDerivedPred :: PredType -> Message
1322 badDerivedPred pred
1323   = vcat [ptext (sLit "Can't derive instances where the instance context mentions"),
1324           ptext (sLit "type variables that are not data type parameters"),
1325           nest 2 (ptext (sLit "Offending constraint:") <+> ppr pred)]
1326 \end{code}