Don't import FastString in HsVersions.h
[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],         -- 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         ; early_specs <- makeDerivSpecs tycl_decls inst_decls deriv_decls
273
274         ; overlap_flag <- getOverlapFlag
275         ; let (infer_specs, given_specs) = splitEithers early_specs
276         ; (insts1, aux_binds1) <- mapAndUnzipM (genInst overlap_flag) given_specs
277
278         ; final_specs <- extendLocalInstEnv (map iSpec insts1) $
279                          inferInstanceContexts overlap_flag infer_specs
280
281         ; (insts2, aux_binds2) <- mapAndUnzipM (genInst overlap_flag) final_specs
282
283         ; is_boot <- tcIsHsBoot
284         ; rn_binds <- makeAuxBinds is_boot tycl_decls
285                                    (concat aux_binds1 ++ concat aux_binds2)
286
287         ; let inst_info = 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] -> HsValBinds Name -> SDoc
296     ddump_deriving inst_infos extra_binds
297       = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
298
299 makeAuxBinds :: Bool -> [LTyClDecl Name] -> DerivAuxBinds -> TcM (HsValBinds Name)
300 makeAuxBinds is_boot tycl_decls deriv_aux_binds
301   | is_boot     -- If we are compiling a hs-boot file, 
302                 -- don't generate any derived bindings
303   = return emptyValBindsOut
304
305   | otherwise
306   = do  { let aux_binds = listToBag (map genAuxBind (rm_dups [] deriv_aux_binds))
307                 -- Generate any extra not-one-inst-decl-specific binds, 
308                 -- notably "con2tag" and/or "tag2con" functions.  
309
310         -- Generate the generic to/from functions from each type declaration
311         ; gen_binds <- mkGenericBinds tycl_decls
312
313         -- Rename these extra bindings, discarding warnings about unused bindings etc
314         -- Type signatures in patterns are used in the generic binds
315         ; discardWarnings $
316           setOptM Opt_PatternSignatures $
317           do    { (rn_deriv, _dus1) <- rnTopBinds (ValBindsIn aux_binds [])
318                 ; (rn_gen, dus_gen) <- rnTopBinds (ValBindsIn gen_binds [])
319                 ; keepAliveSetTc (duDefs dus_gen)       -- Mark these guys to
320                                                         -- be kept alive
321                 ; return (rn_deriv `plusHsValBinds` rn_gen) } }
322   where
323         -- Remove duplicate requests for auxilliary bindings
324     rm_dups acc [] = acc
325     rm_dups acc (b:bs) | any (isDupAux b) acc = rm_dups acc bs
326                        | otherwise            = rm_dups (b:acc) bs
327
328 -----------------------------------------
329 mkGenericBinds :: [LTyClDecl Name] -> TcM (LHsBinds RdrName)
330 mkGenericBinds tycl_decls
331   = do  { tcs <- mapM tcLookupTyCon 
332                         [ tc_name | 
333                           L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
334                 -- We are only interested in the data type declarations
335         ; return (unionManyBags [ mkTyConGenericBinds tc | 
336                                   tc <- tcs, tyConHasGenerics tc ]) }
337                 -- And then only in the ones whose 'has-generics' flag is on
338 \end{code}
339
340
341 %************************************************************************
342 %*                                                                      *
343                 From HsSyn to DerivSpec
344 %*                                                                      *
345 %************************************************************************
346
347 @makeDerivSpecs@ fishes around to find the info about needed derived
348 instances.  Complicating factors:
349 \begin{itemize}
350 \item
351 We can only derive @Enum@ if the data type is an enumeration
352 type (all nullary data constructors).
353
354 \item
355 We can only derive @Ix@ if the data type is an enumeration {\em
356 or} has just one data constructor (e.g., tuples).
357 \end{itemize}
358
359 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
360 all those.
361
362 \begin{code}
363 makeDerivSpecs :: [LTyClDecl Name] 
364                -> [LInstDecl Name]
365                -> [LDerivDecl Name] 
366                -> TcM [EarlyDerivSpec]
367
368 makeDerivSpecs tycl_decls inst_decls deriv_decls
369   = do  { eqns1 <- mapAndRecoverM deriveTyData $
370                      extractTyDataPreds tycl_decls ++
371                      [ pd                        -- traverse assoc data families
372                      | L _ (InstDecl _ _ _ ats) <- inst_decls
373                      , pd <- extractTyDataPreds ats ]
374         ; eqns2 <- mapAndRecoverM deriveStandalone deriv_decls
375         ; return (catMaybes (eqns1 ++ eqns2)) }
376   where
377     extractTyDataPreds decls =             
378       [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
379
380
381 ------------------------------------------------------------------
382 deriveStandalone :: LDerivDecl Name -> TcM (Maybe EarlyDerivSpec)
383 -- Standalone deriving declarations
384 --  e.g.   deriving instance show a => Show (T a)
385 -- Rather like tcLocalInstDecl
386 deriveStandalone (L loc (DerivDecl deriv_ty))
387   = setSrcSpan loc                   $
388     addErrCtxt (standaloneCtxt deriv_ty)  $
389     do { traceTc (text "standalone deriving decl for" <+> ppr deriv_ty)
390        ; (tvs, theta, tau) <- tcHsInstHead deriv_ty
391        ; traceTc (text "standalone deriving;"
392               <+> text "tvs:" <+> ppr tvs
393               <+> text "theta:" <+> ppr theta
394               <+> text "tau:" <+> ppr tau)
395        ; (cls, inst_tys) <- checkValidInstHead tau
396        ; let cls_tys = take (length inst_tys - 1) inst_tys
397              inst_ty = last inst_tys
398
399        ; traceTc (text "standalone deriving;"
400               <+> text "class:" <+> ppr cls
401               <+> text "class types:" <+> ppr cls_tys
402               <+> text "type:" <+> ppr inst_ty)
403        ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
404                    (Just theta) }
405
406 ------------------------------------------------------------------
407 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM (Maybe EarlyDerivSpec)
408 deriveTyData (deriv_pred, L loc decl@(TyData { tcdLName = L _ tycon_name, 
409                                                tcdTyVars = tv_names, 
410                                                tcdTyPats = ty_pats }))
411   = setSrcSpan loc                   $
412     tcAddDeclCtxt decl               $
413     do  { let hs_ty_args = ty_pats `orElse` map (nlHsTyVar . hsLTyVarName) tv_names
414               hs_app     = nlHsTyConApp tycon_name hs_ty_args
415                 -- We get kinding info for the tyvars by typechecking (T a b)
416                 -- Hence forming a tycon application and then dis-assembling it
417         ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
418         ; tcExtendTyVarEnv tvs $        -- Deriving preds may (now) mention
419                                         -- the type variables for the type constructor
420     do  { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
421                 -- The "deriv_pred" is a LHsType to take account of the fact that for
422                 -- newtype deriving we allow deriving (forall a. C [a]).
423         ; mkEqnHelp DerivOrigin (tvs++deriv_tvs) cls cls_tys tc_app Nothing } }
424
425 deriveTyData _other
426   = panic "derivTyData" -- Caller ensures that only TyData can happen
427
428 ------------------------------------------------------------------
429 mkEqnHelp :: InstOrigin -> [TyVar] -> Class -> [Type] -> Type
430           -> Maybe ThetaType    -- Just    => context supplied (standalone deriving)
431                                 -- Nothing => context inferred (deriving on data decl)
432           -> TcRn (Maybe EarlyDerivSpec)
433 mkEqnHelp orig tvs cls cls_tys tc_app mtheta
434   | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
435   = do  {
436         -- For standalone deriving (mtheta /= Nothing), 
437         -- check that all the data constructors are in scope
438         -- By this time we know that the thing is algebraic
439         --      because we've called checkInstHead in derivingStandalone
440           rdr_env <- getGlobalRdrEnv
441         ; let hidden_data_cons = filter not_in_scope (tyConDataCons tycon)
442               not_in_scope dc = null (lookupGRE_Name rdr_env (dataConName dc))
443         ; checkTc (isNothing mtheta || null hidden_data_cons) 
444                   (derivingHiddenErr tycon)
445
446         ; mayDeriveDataTypeable <- doptM Opt_DeriveDataTypeable
447         ; newtype_deriving <- doptM Opt_GeneralizedNewtypeDeriving
448
449         ; (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon tc_args
450
451           -- Be careful to test rep_tc here: in the case of families, we want
452           -- to check the instance tycon, not the family tycon
453         ; if isDataTyCon rep_tc then
454                 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys 
455                               tycon tc_args rep_tc rep_tc_args mtheta
456           else
457                 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving
458                              tvs cls cls_tys 
459                              tycon tc_args rep_tc rep_tc_args mtheta }
460   | otherwise
461   = baleOut (derivingThingErr cls cls_tys tc_app
462                 (ptext SLIT("Last argument of the instance must be a type application")))
463
464 baleOut :: Message -> TcM (Maybe a)
465 baleOut err = do { addErrTc err;  return Nothing }
466 \end{code}
467
468 Auxiliary lookup wrapper which requires that looked up family instances are
469 not type instances.  If called with a vanilla tycon, the old type application
470 is simply returned.
471
472 \begin{code}
473 tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
474 tcLookupFamInstExact tycon tys
475   | not (isOpenTyCon tycon)
476   = return (tycon, tys)
477   | otherwise
478   = do { maybeFamInst <- tcLookupFamInst tycon tys
479        ; case maybeFamInst of
480            Nothing                     -> famInstNotFound tycon tys False
481            Just famInst@(_, rep_tys)
482              | not variable_only_subst -> famInstNotFound tycon tys True
483              | otherwise               -> return famInst
484              where
485                tvs                  = map (Type.getTyVar 
486                                              "TcDeriv.tcLookupFamInstExact") 
487                                           rep_tys
488                variable_only_subst  = all Type.isTyVarTy rep_tys &&
489                                       sizeVarSet (mkVarSet tvs) == length tvs
490                                         -- renaming may have no repetitions
491        }
492 \end{code}
493
494
495 %************************************************************************
496 %*                                                                      *
497                 Deriving data types
498 %*                                                                      *
499 %************************************************************************
500
501 \begin{code}
502 mkDataTypeEqn :: InstOrigin -> Bool -> [Var] -> Class -> [Type]
503               -> TyCon -> [Type] -> TyCon -> [Type] -> Maybe ThetaType
504               -> TcRn (Maybe EarlyDerivSpec)    -- Return 'Nothing' if error
505                 
506 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
507               tycon tc_args rep_tc rep_tc_args mtheta
508   | Just err <- checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
509         -- NB: pass the *representation* tycon to checkSideConditions
510   = baleOut (derivingThingErr cls cls_tys (mkTyConApp tycon tc_args) err)
511
512   | otherwise 
513   = ASSERT( null cls_tys )
514     mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
515
516 mk_data_eqn, mk_typeable_eqn
517    :: InstOrigin -> [TyVar] -> Class 
518    -> TyCon -> [TcType] -> TyCon -> [TcType] -> Maybe ThetaType
519    -> TcM (Maybe EarlyDerivSpec)
520 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
521   | getName cls `elem` typeableClassNames
522   = mk_typeable_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
523
524   | otherwise
525   = do  { dfun_name <- new_dfun_name cls tycon
526         ; loc <- getSrcSpanM
527         ; let ordinary_constraints
528                 = [ mkClassPred cls [arg_ty] 
529                   | data_con <- tyConDataCons rep_tc,
530                     arg_ty   <- ASSERT( isVanillaDataCon data_con )
531                                 dataConInstOrigArgTys data_con rep_tc_args,
532                     not (isUnLiftedType arg_ty) ] -- No constraints for unlifted types?
533
534                         -- See Note [Superclasses of derived instance]
535               sc_constraints = substTheta (zipOpenTvSubst (classTyVars cls) inst_tys)
536                                           (classSCTheta cls)
537               inst_tys =  [mkTyConApp tycon tc_args]
538
539               stupid_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
540               stupid_constraints = substTheta stupid_subst (tyConStupidTheta rep_tc)
541               all_constraints = stupid_constraints ++ sc_constraints ++ ordinary_constraints
542
543               spec = DS { ds_loc = loc, ds_orig = orig
544                         , ds_name = dfun_name, ds_tvs = tvs 
545                         , ds_cls = cls, ds_tys = inst_tys
546                         , ds_theta =  mtheta `orElse` all_constraints
547                         , ds_newtype = False }
548
549         ; return (if isJust mtheta then Just (Right spec)       -- Specified context
550                                    else Just (Left spec)) }     -- Infer context
551
552 mk_typeable_eqn orig tvs cls tycon tc_args rep_tc _rep_tc_args mtheta
553         -- The Typeable class is special in several ways
554         --        data T a b = ... deriving( Typeable )
555         -- gives
556         --        instance Typeable2 T where ...
557         -- Notice that:
558         -- 1. There are no constraints in the instance
559         -- 2. There are no type variables either
560         -- 3. The actual class we want to generate isn't necessarily
561         --      Typeable; it depends on the arity of the type
562   | isNothing mtheta    -- deriving on a data type decl
563   = do  { checkTc (cls `hasKey` typeableClassKey)
564                   (ptext SLIT("Use deriving( Typeable ) on a data type declaration"))
565         ; real_cls <- tcLookupClass (typeableClassNames !! tyConArity tycon)
566         ; mk_typeable_eqn orig tvs real_cls tycon [] rep_tc [] (Just []) }
567
568   | otherwise           -- standaone deriving
569   = do  { checkTc (null tc_args)
570                   (ptext SLIT("Derived typeable instance must be of form (Typeable") 
571                         <> int (tyConArity tycon) <+> ppr tycon <> rparen)
572         ; dfun_name <- new_dfun_name cls tycon
573         ; loc <- getSrcSpanM
574         ; return (Just $ Right $
575                   DS { ds_loc = loc, ds_orig = orig, ds_name = dfun_name, ds_tvs = []
576                      , ds_cls = cls, ds_tys = [mkTyConApp tycon []] 
577                      , ds_theta = mtheta `orElse` [], ds_newtype = False })  }
578
579 ------------------------------------------------------------------
580 -- Check side conditions that dis-allow derivability for particular classes
581 -- This is *apart* from the newtype-deriving mechanism
582 --
583 -- Here we get the representation tycon in case of family instances as it has
584 -- the data constructors - but we need to be careful to fall back to the
585 -- family tycon (with indexes) in error messages.
586
587 checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> Maybe SDoc
588 checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
589   | notNull cls_tys     
590   = Just ty_args_why    -- e.g. deriving( Foo s )
591   | otherwise
592   = case sideConditions cls of
593         Just cond -> cond (mayDeriveDataTypeable, rep_tc)
594         Nothing   -> Just non_std_why
595   where
596     ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("is not a class")
597     non_std_why = quotes (ppr cls) <+> ptext SLIT("is not a derivable class")
598
599 sideConditions :: Class -> Maybe Condition
600 sideConditions cls
601   | cls_key == eqClassKey   = Just cond_std
602   | cls_key == ordClassKey  = Just cond_std
603   | cls_key == readClassKey = Just cond_std
604   | cls_key == showClassKey = Just cond_std
605   | cls_key == enumClassKey = Just (cond_std `andCond` cond_isEnumeration)
606   | cls_key == ixClassKey   = Just (cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct))
607   | cls_key == boundedClassKey = Just (cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct))
608   | cls_key == dataClassKey    = Just (cond_mayDeriveDataTypeable `andCond` cond_std)
609   | getName cls `elem` typeableClassNames = Just (cond_mayDeriveDataTypeable `andCond` cond_typeableOK)
610   | otherwise = Nothing
611   where
612     cls_key = getUnique cls
613
614 type Condition = (Bool, TyCon) -> Maybe SDoc
615         -- Bool is whether or not we are allowed to derive Data and Typeable
616         -- TyCon is the *representation* tycon if the 
617         --      data type is an indexed one
618         -- Nothing => OK
619
620 orCond :: Condition -> Condition -> Condition
621 orCond c1 c2 tc 
622   = case c1 tc of
623         Nothing -> Nothing              -- c1 succeeds
624         Just x  -> case c2 tc of        -- c1 fails
625                      Nothing -> Nothing
626                      Just y  -> Just (x $$ ptext SLIT("  and") $$ y)
627                                         -- Both fail
628
629 andCond :: Condition -> Condition -> Condition
630 andCond c1 c2 tc = case c1 tc of
631                      Nothing -> c2 tc   -- c1 succeeds
632                      Just x  -> Just x  -- c1 fails
633
634 cond_std :: Condition
635 cond_std (_, rep_tc)
636   | any (not . isVanillaDataCon) data_cons = Just existential_why     
637   | null data_cons                         = Just no_cons_why
638   | otherwise                              = Nothing
639   where
640     data_cons       = tyConDataCons rep_tc
641     no_cons_why     = quotes (pprSourceTyCon rep_tc) <+> 
642                       ptext SLIT("has no data constructors")
643     existential_why = quotes (pprSourceTyCon rep_tc) <+> 
644                       ptext SLIT("has non-Haskell-98 constructor(s)")
645   
646 cond_isEnumeration :: Condition
647 cond_isEnumeration (_, rep_tc)
648   | isEnumerationTyCon rep_tc = Nothing
649   | otherwise                 = Just why
650   where
651     why = quotes (pprSourceTyCon rep_tc) <+> 
652           ptext SLIT("has non-nullary constructors")
653
654 cond_isProduct :: Condition
655 cond_isProduct (_, rep_tc)
656   | isProductTyCon rep_tc = Nothing
657   | otherwise             = Just why
658   where
659     why = quotes (pprSourceTyCon rep_tc) <+> 
660           ptext SLIT("has more than one constructor")
661
662 cond_typeableOK :: Condition
663 -- OK for Typeable class
664 -- Currently: (a) args all of kind *
665 --            (b) 7 or fewer args
666 cond_typeableOK (_, rep_tc)
667   | tyConArity rep_tc > 7       = Just too_many
668   | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc)) 
669                                 = Just bad_kind
670   | isFamInstTyCon rep_tc       = Just fam_inst  -- no Typable for family insts
671   | otherwise                   = Nothing
672   where
673     too_many = quotes (pprSourceTyCon rep_tc) <+> 
674                ptext SLIT("has too many arguments")
675     bad_kind = quotes (pprSourceTyCon rep_tc) <+> 
676                ptext SLIT("has arguments of kind other than `*'")
677     fam_inst = quotes (pprSourceTyCon rep_tc) <+> 
678                ptext SLIT("is a type family")
679
680 cond_mayDeriveDataTypeable :: Condition
681 cond_mayDeriveDataTypeable (mayDeriveDataTypeable, _)
682  | mayDeriveDataTypeable = Nothing
683  | otherwise = Just why
684   where
685     why  = ptext SLIT("You need -XDeriveDataTypeable to derive an instance for this class")
686
687 std_class_via_iso :: Class -> Bool
688 std_class_via_iso clas  -- These standard classes can be derived for a newtype
689                         -- using the isomorphism trick *even if no -fglasgow-exts*
690   = classKey clas `elem`  [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
691         -- Not Read/Show because they respect the type
692         -- Not Enum, because newtypes are never in Enum
693
694
695 new_dfun_name :: Class -> TyCon -> TcM Name
696 new_dfun_name clas tycon        -- Just a simple wrapper
697   = newDFunName clas [mkTyConApp tycon []] (getSrcSpan tycon)
698         -- The type passed to newDFunName is only used to generate
699         -- a suitable string; hence the empty type arg list
700 \end{code}
701
702 Note [Superclasses of derived instance] 
703 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
704 In general, a derived instance decl needs the superclasses of the derived
705 class too.  So if we have
706         data T a = ...deriving( Ord )
707 then the initial context for Ord (T a) should include Eq (T a).  Often this is 
708 redundant; we'll also generate an Ord constraint for each constructor argument,
709 and that will probably generate enough constraints to make the Eq (T a) constraint 
710 be satisfied too.  But not always; consider:
711
712  data S a = S
713  instance Eq (S a)
714  instance Ord (S a)
715
716  data T a = MkT (S a) deriving( Ord )
717  instance Num a => Eq (T a)
718
719 The derived instance for (Ord (T a)) must have a (Num a) constraint!
720 Similarly consider:
721         data T a = MkT deriving( Data, Typeable )
722 Here there *is* no argument field, but we must nevertheless generate
723 a context for the Data instances:
724         instance Typable a => Data (T a) where ...
725
726
727 %************************************************************************
728 %*                                                                      *
729                 Deriving newtypes
730 %*                                                                      *
731 %************************************************************************
732
733 \begin{code}
734 mkNewTypeEqn :: InstOrigin -> Bool -> Bool -> [Var] -> Class
735              -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
736              -> Maybe ThetaType
737              -> TcRn (Maybe EarlyDerivSpec)
738 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving tvs
739              cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
740   | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
741   = do  { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
742         ; dfun_name <- new_dfun_name cls tycon
743         ; loc <- getSrcSpanM
744         ; let spec = DS { ds_loc = loc, ds_orig = orig
745                         , ds_name = dfun_name, ds_tvs = dict_tvs 
746                         , ds_cls = cls, ds_tys = inst_tys
747                         , ds_theta =  mtheta `orElse` all_preds
748                         , ds_newtype = True }
749         ; return (if isJust mtheta then Just (Right spec)
750                                    else Just (Left spec)) }
751
752   | isNothing mb_std_err        -- Use the standard H98 method
753   = mk_data_eqn orig tvs cls tycon tc_args rep_tycon rep_tc_args mtheta
754
755         -- Otherwise we can't derive
756   | newtype_deriving = baleOut cant_derive_err -- Too hard
757   | otherwise        = baleOut std_err          -- Just complain about being a non-std instance
758   where
759         mb_std_err = checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tycon
760         std_err = derivingThingErr cls cls_tys tc_app $
761                   vcat [fromJust mb_std_err,
762                         ptext SLIT("Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")]
763
764         -- Here is the plan for newtype derivings.  We see
765         --        newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
766         -- where t is a type,
767         --       ak+1...an is a suffix of a1..an, and are all tyars
768         --       ak+1...an do not occur free in t, nor in the s1..sm
769         --       (C s1 ... sm) is a  *partial applications* of class C 
770         --                      with the last parameter missing
771         --       (T a1 .. ak) matches the kind of C's last argument
772         --              (and hence so does t)
773         --
774         -- We generate the instance
775         --       instance forall ({a1..ak} u fvs(s1..sm)).
776         --                C s1 .. sm t => C s1 .. sm (T a1...ak)
777         -- where T a1...ap is the partial application of 
778         --       the LHS of the correct kind and p >= k
779         --
780         --      NB: the variables below are:
781         --              tc_tvs = [a1, ..., an]
782         --              tyvars_to_keep = [a1, ..., ak]
783         --              rep_ty = t ak .. an
784         --              deriv_tvs = fvs(s1..sm) \ tc_tvs
785         --              tys = [s1, ..., sm]
786         --              rep_fn' = t
787         --
788         -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
789         -- We generate the instance
790         --      instance Monad (ST s) => Monad (T s) where 
791
792         cls_tyvars = classTyVars cls
793         kind = tyVarKind (last cls_tyvars)
794                 -- Kind of the thing we want to instance
795                 --   e.g. argument kind of Monad, *->*
796
797         (arg_kinds, _) = splitKindFunTys kind
798         n_args_to_drop = length arg_kinds       
799                 -- Want to drop 1 arg from (T s a) and (ST s a)
800                 -- to get       instance Monad (ST s) => Monad (T s)
801
802         -- Note [Newtype representation]
803         -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
804         -- Need newTyConRhs (*not* a recursive representation finder) 
805         -- to get the representation type. For example
806         --      newtype B = MkB Int
807         --      newtype A = MkA B deriving( Num )
808         -- We want the Num instance of B, *not* the Num instance of Int,
809         -- when making the Num instance of A!
810         rep_ty                = newTyConInstRhs rep_tycon rep_tc_args
811         (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
812
813         n_tyargs_to_keep = tyConArity tycon - n_args_to_drop
814         dropped_tc_args = drop n_tyargs_to_keep tc_args
815         dropped_tvs     = tyVarsOfTypes dropped_tc_args
816
817         n_args_to_keep = length rep_ty_args - n_args_to_drop
818         args_to_drop   = drop n_args_to_keep rep_ty_args
819         args_to_keep   = take n_args_to_keep rep_ty_args
820
821         rep_fn'  = mkAppTys rep_fn args_to_keep
822         rep_tys  = cls_tys ++ [rep_fn']
823         rep_pred = mkClassPred cls rep_tys
824                 -- rep_pred is the representation dictionary, from where
825                 -- we are gong to get all the methods for the newtype
826                 -- dictionary 
827
828         tc_app = mkTyConApp tycon (take n_tyargs_to_keep tc_args)
829
830     -- Next we figure out what superclass dictionaries to use
831     -- See Note [Newtype deriving superclasses] above
832
833         inst_tys = cls_tys ++ [tc_app]
834         sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
835                               (classSCTheta cls)
836
837                 -- If there are no tyvars, there's no need
838                 -- to abstract over the dictionaries we need
839                 -- Example:     newtype T = MkT Int deriving( C )
840                 -- We get the derived instance
841                 --              instance C T
842                 -- rather than
843                 --              instance C Int => C T
844         dict_tvs = filterOut (`elemVarSet` dropped_tvs) tvs
845         all_preds = rep_pred : sc_theta         -- NB: rep_pred comes first
846
847         -------------------------------------------------------------------
848         --  Figuring out whether we can only do this newtype-deriving thing
849
850         right_arity = length cls_tys + 1 == classArity cls
851
852                 -- Never derive Read,Show,Typeable,Data this way 
853         non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
854         can_derive_via_isomorphism
855            =  not (getUnique cls `elem` non_iso_classes)
856            && right_arity                       -- Well kinded;
857                                                 -- eg not: newtype T ... deriving( ST )
858                                                 --      because ST needs *2* type params
859            && n_tyargs_to_keep >= 0             -- Type constructor has right kind:
860                                                 -- eg not: newtype T = T Int deriving( Monad )
861            && n_args_to_keep   >= 0             -- Rep type has right kind: 
862                                                 -- eg not: newtype T a = T Int deriving( Monad )
863            && eta_ok                            -- Eta reduction works
864            && not (isRecursiveTyCon tycon)      -- Does not work for recursive tycons:
865                                                 --      newtype A = MkA [A]
866                                                 -- Don't want
867                                                 --      instance Eq [A] => Eq A !!
868                         -- Here's a recursive newtype that's actually OK
869                         --      newtype S1 = S1 [T1 ()]
870                         --      newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
871                         -- It's currently rejected.  Oh well.
872                         -- In fact we generate an instance decl that has method of form
873                         --      meth @ instTy = meth @ repTy
874                         -- (no coerce's).  We'd need a coerce if we wanted to handle
875                         -- recursive newtypes too
876
877         -- Check that eta reduction is OK
878         eta_ok = (args_to_drop `tcEqTypes` dropped_tc_args)
879                 -- (a) the dropped-off args are identical in the source and rep type
880                 --        newtype T a b = MkT (S [a] b) deriving( Monad )
881                 --     Here the 'b' must be the same in the rep type (S [a] b)
882
883               && (tyVarsOfType rep_fn' `disjointVarSet` dropped_tvs)
884                 -- (b) the remaining type args do not mention any of the dropped
885                 --     type variables 
886
887               && (tyVarsOfTypes cls_tys `disjointVarSet` dropped_tvs)
888                 -- (c) the type class args do not mention any of the dropped type
889                 --     variables 
890
891               && all isTyVarTy dropped_tc_args
892                 -- (d) in case of newtype family instances, the eta-dropped
893                 --      arguments must be type variables (not more complex indexes)
894
895         cant_derive_err = derivingThingErr cls cls_tys tc_app
896                                 (vcat [ptext SLIT("even with cunning newtype deriving:"),
897                                         if isRecursiveTyCon tycon then
898                                           ptext SLIT("the newtype may be recursive")
899                                         else empty,
900                                         if not right_arity then 
901                                           quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("does not have arity 1")
902                                         else empty,
903                                         if not (n_tyargs_to_keep >= 0) then 
904                                           ptext SLIT("the type constructor has wrong kind")
905                                         else if not (n_args_to_keep >= 0) then
906                                           ptext SLIT("the representation type has wrong kind")
907                                         else if not eta_ok then 
908                                           ptext SLIT("the eta-reduction property does not hold")
909                                         else empty
910                                       ])
911 \end{code}
912
913
914 %************************************************************************
915 %*                                                                      *
916 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
917 %*                                                                      *
918 %************************************************************************
919
920 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
921 terms, which is the final correct RHS for the corresponding original
922 equation.
923 \begin{itemize}
924 \item
925 Each (k,TyVarTy tv) in a solution constrains only a type
926 variable, tv.
927
928 \item
929 The (k,TyVarTy tv) pairs in a solution are canonically
930 ordered by sorting on type varible, tv, (major key) and then class, k,
931 (minor key)
932 \end{itemize}
933
934 \begin{code}
935 inferInstanceContexts :: OverlapFlag -> [DerivSpec] -> TcM [DerivSpec]
936
937 inferInstanceContexts _ [] = return []
938
939 inferInstanceContexts oflag infer_specs
940   = do  { traceTc (text "inferInstanceContexts" <+> vcat (map pprDerivSpec infer_specs))
941         ; iterate_deriv 1 initial_solutions }
942   where
943     ------------------------------------------------------------------
944         -- The initial solutions for the equations claim that each
945         -- instance has an empty context; this solution is certainly
946         -- in canonical form.
947     initial_solutions :: [ThetaType]
948     initial_solutions = [ [] | _ <- infer_specs ]
949
950     ------------------------------------------------------------------
951         -- iterate_deriv calculates the next batch of solutions,
952         -- compares it with the current one; finishes if they are the
953         -- same, otherwise recurses with the new solutions.
954         -- It fails if any iteration fails
955     iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec]
956     iterate_deriv n current_solns
957       | n > 20  -- Looks as if we are in an infinite loop
958                 -- This can happen if we have -fallow-undecidable-instances
959                 -- (See TcSimplify.tcSimplifyDeriv.)
960       = pprPanic "solveDerivEqns: probable loop" 
961                  (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
962       | otherwise
963       = do {      -- Extend the inst info from the explicit instance decls
964                   -- with the current set of solutions, and simplify each RHS
965              let inst_specs = zipWithEqual "add_solns" (mkInstance2 oflag)
966                                            current_solns infer_specs
967            ; new_solns <- checkNoErrs $
968                           extendLocalInstEnv inst_specs $
969                           mapM gen_soln infer_specs
970
971            ; if (current_solns == new_solns) then
972                 return [ spec { ds_theta = soln } 
973                        | (spec, soln) <- zip infer_specs current_solns ]
974              else
975                 iterate_deriv (n+1) new_solns }
976
977     ------------------------------------------------------------------
978     gen_soln :: DerivSpec  -> TcM [PredType]
979     gen_soln (DS { ds_loc = loc, ds_orig = orig, ds_tvs = tyvars 
980                  , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
981       = setSrcSpan loc  $
982         addErrCtxt (derivInstCtxt clas inst_tys) $ 
983         do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
984                 -- checkValidInstance tyvars theta clas inst_tys
985                 -- Not necessary; see Note [Exotic derived instance contexts]
986                 --                in TcSimplify
987
988                   -- Check for a bizarre corner case, when the derived instance decl should
989                   -- have form  instance C a b => D (T a) where ...
990                   -- Note that 'b' isn't a parameter of T.  This gives rise to all sorts
991                   -- of problems; in particular, it's hard to compare solutions for
992                   -- equality when finding the fixpoint.  So I just rule it out for now.
993            ; let tv_set = mkVarSet tyvars
994                  weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]  
995            ; mapM_ (addErrTc . badDerivedPred) weird_preds      
996
997                 -- Claim: the result instance declaration is guaranteed valid
998                 -- Hence no need to call:
999                 --   checkValidInstance tyvars theta clas inst_tys
1000            ; return (sortLe (<=) theta) }       -- Canonicalise before returning the solution
1001
1002 ------------------------------------------------------------------
1003 mkInstance1 :: OverlapFlag -> DerivSpec -> Instance
1004 mkInstance1 overlap_flag spec = mkInstance2 overlap_flag (ds_theta spec) spec
1005
1006 mkInstance2 :: OverlapFlag -> ThetaType -> DerivSpec -> Instance
1007 mkInstance2 overlap_flag theta
1008             (DS { ds_name = dfun_name
1009                 , ds_tvs = tyvars, ds_cls = clas, ds_tys = tys })
1010   = mkLocalInstance dfun overlap_flag
1011   where
1012     dfun = mkDictFunId dfun_name tyvars theta clas tys
1013
1014
1015 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
1016 -- Add new locally-defined instances; don't bother to check
1017 -- for functional dependency errors -- that'll happen in TcInstDcls
1018 extendLocalInstEnv dfuns thing_inside
1019  = do { env <- getGblEnv
1020       ; let  inst_env' = extendInstEnvList (tcg_inst_env env) dfuns 
1021              env'      = env { tcg_inst_env = inst_env' }
1022       ; setGblEnv env' thing_inside }
1023 \end{code}
1024
1025
1026 %************************************************************************
1027 %*                                                                      *
1028 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
1029 %*                                                                      *
1030 %************************************************************************
1031
1032 After all the trouble to figure out the required context for the
1033 derived instance declarations, all that's left is to chug along to
1034 produce them.  They will then be shoved into @tcInstDecls2@, which
1035 will do all its usual business.
1036
1037 There are lots of possibilities for code to generate.  Here are
1038 various general remarks.
1039
1040 PRINCIPLES:
1041 \begin{itemize}
1042 \item
1043 We want derived instances of @Eq@ and @Ord@ (both v common) to be
1044 ``you-couldn't-do-better-by-hand'' efficient.
1045
1046 \item
1047 Deriving @Show@---also pretty common--- should also be reasonable good code.
1048
1049 \item
1050 Deriving for the other classes isn't that common or that big a deal.
1051 \end{itemize}
1052
1053 PRAGMATICS:
1054
1055 \begin{itemize}
1056 \item
1057 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
1058
1059 \item
1060 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
1061
1062 \item
1063 We {\em normally} generate code only for the non-defaulted methods;
1064 there are some exceptions for @Eq@ and (especially) @Ord@...
1065
1066 \item
1067 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
1068 constructor's numeric (@Int#@) tag.  These are generated by
1069 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
1070 these is around is given by @hasCon2TagFun@.
1071
1072 The examples under the different sections below will make this
1073 clearer.
1074
1075 \item
1076 Much less often (really just for deriving @Ix@), we use a
1077 @_tag2con_<tycon>@ function.  See the examples.
1078
1079 \item
1080 We use the renamer!!!  Reason: we're supposed to be
1081 producing @LHsBinds Name@ for the methods, but that means
1082 producing correctly-uniquified code on the fly.  This is entirely
1083 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
1084 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
1085 the renamer.  What a great hack!
1086 \end{itemize}
1087
1088 \begin{code}
1089 -- Generate the InstInfo for the required instance paired with the
1090 --   *representation* tycon for that instance,
1091 -- plus any auxiliary bindings required
1092 --
1093 -- Representation tycons differ from the tycon in the instance signature in
1094 -- case of instances for indexed families.
1095 --
1096 genInst :: OverlapFlag -> DerivSpec -> TcM (InstInfo, DerivAuxBinds)
1097 genInst oflag spec
1098   | ds_newtype spec
1099   = return (InstInfo { iSpec = mkInstance1 oflag spec 
1100                      , iBinds = NewTypeDerived }, [])
1101
1102   | otherwise
1103   = do  { fix_env <- getFixityEnv
1104         ; let
1105             inst                    = mkInstance1 oflag spec
1106             (tyvars,_,clas,[ty])    = instanceHead inst
1107             clas_nm                 = className clas
1108             (visible_tycon, tyArgs) = tcSplitTyConApp ty 
1109
1110           -- In case of a family instance, we need to use the representation
1111           -- tycon (after all, it has the data constructors)
1112         ; (tycon, _) <- tcLookupFamInstExact visible_tycon tyArgs
1113         ; let (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
1114
1115         -- Bring the right type variables into 
1116         -- scope, and rename the method binds
1117         -- It's a bit yukky that we return *renamed* InstInfo, but
1118         -- *non-renamed* auxiliary bindings
1119         ; (rn_meth_binds, _fvs) <- discardWarnings $ 
1120                                    bindLocalNames (map Var.varName tyvars) $
1121                                    rnMethodBinds clas_nm (\_ -> []) [] meth_binds
1122
1123         -- Build the InstInfo
1124         ; return (InstInfo { iSpec = inst, 
1125                              iBinds = VanillaInst rn_meth_binds [] },
1126                   aux_binds)
1127         }
1128
1129 genDerivBinds :: Class -> FixityEnv -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1130 genDerivBinds clas fix_env tycon
1131   | className clas `elem` typeableClassNames
1132   = (gen_Typeable_binds tycon, [])
1133
1134   | otherwise
1135   = case assocMaybe gen_list (getUnique clas) of
1136         Just gen_fn -> gen_fn tycon
1137         Nothing     -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1138   where
1139     gen_list :: [(Unique, TyCon -> (LHsBinds RdrName, DerivAuxBinds))]
1140     gen_list = [(eqClassKey,       gen_Eq_binds)
1141                ,(ordClassKey,      gen_Ord_binds)
1142                ,(enumClassKey,     gen_Enum_binds)
1143                ,(boundedClassKey,  gen_Bounded_binds)
1144                ,(ixClassKey,       gen_Ix_binds)
1145                ,(showClassKey,     gen_Show_binds fix_env)
1146                ,(readClassKey,     gen_Read_binds fix_env)
1147                ,(dataClassKey,     gen_Data_binds fix_env)
1148                ]
1149 \end{code}
1150
1151
1152 %************************************************************************
1153 %*                                                                      *
1154 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1155 %*                                                                      *
1156 %************************************************************************
1157
1158 \begin{code}
1159 derivingThingErr :: Class -> [Type] -> Type -> Message -> Message
1160 derivingThingErr clas tys ty why
1161   = sep [hsep [ptext SLIT("Can't make a derived instance of"), 
1162                quotes (ppr pred)],
1163          nest 2 (parens why)]
1164   where
1165     pred = mkClassPred clas (tys ++ [ty])
1166
1167 derivingHiddenErr :: TyCon -> SDoc
1168 derivingHiddenErr tc
1169   = hang (ptext SLIT("The data constructors of") <+> quotes (ppr tc) <+> ptext SLIT("are not all in scope"))
1170        2 (ptext SLIT("so you cannot derive an instance for it"))
1171
1172 standaloneCtxt :: LHsType Name -> SDoc
1173 standaloneCtxt ty = hang (ptext SLIT("In the stand-alone deriving instance for")) 
1174                        2 (quotes (ppr ty))
1175
1176 derivInstCtxt :: Class -> [Type] -> Message
1177 derivInstCtxt clas inst_tys
1178   = ptext SLIT("When deriving the instance for") <+> parens (pprClassPred clas inst_tys)
1179
1180 badDerivedPred :: PredType -> Message
1181 badDerivedPred pred
1182   = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
1183           ptext SLIT("type variables that are not data type parameters"),
1184           nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]
1185
1186 famInstNotFound :: TyCon -> [Type] -> Bool -> TcM a
1187 famInstNotFound tycon tys notExact
1188   = failWithTc (msg <+> quotes (pprTypeApp tycon (ppr tycon) tys))
1189   where
1190     msg = ptext $ if notExact
1191                   then SLIT("No family instance exactly matching")
1192                   else SLIT("More than one family instance for")
1193 \end{code}