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