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