2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Handles @deriving@ clauses on @data@ declarations.
9 module TcDeriv ( tcDeriving ) where
11 #include "HsVersions.h"
19 import TcClassDcl( tcAddDeclCtxt ) -- Small helper
20 import TcGenDeriv -- Deriv stuff
53 %************************************************************************
57 %************************************************************************
61 1. Convert the decls (i.e. data/newtype deriving clauses,
62 plus standalone deriving) to [EarlyDerivSpec]
64 2. Infer the missing contexts for the Left DerivSpecs
66 3. Add the derived bindings, generating InstInfos
69 -- DerivSpec is purely local to this module
70 data DerivSpec = DS { ds_loc :: SrcSpan
71 , ds_orig :: InstOrigin
74 , ds_theta :: ThetaType
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)
85 -- ds_newtype = True <=> Newtype deriving
86 -- False <=> Vanilla deriving
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)
95 -- Right ds => the exact context for the instance is supplied
96 -- by the programmer; it is ds_theta
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)
106 Inferring missing contexts
107 ~~~~~~~~~~~~~~~~~~~~~~~~~~
110 data T a b = C1 (Foo a) (Bar b)
115 [NOTE: See end of these comments for what to do with
116 data (C a, D b) => T a b = ...
119 We want to come up with an instance declaration of the form
121 instance (Ping a, Pong b, ...) => Eq (T a b) where
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.
128 Let's call the context reqd for the T instance of class C at types
129 (a,b, ...) C (T a b). Thus:
131 Eq (T a b) = (Ping a, Pong b, ...)
133 Now we can get a (recursive) equation from the @data@ decl:
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
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.
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.
148 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
152 Eq (T a b) = {} -- The empty set
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
159 After simplification:
160 = Eq a u Ping b u {} u {} u {}
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
169 After simplification:
174 = Eq a u Ping b u Eq b u Ping a
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
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
184 So, here are the synonyms for the ``equation'' structures:
187 Note [Data decl contexts]
188 ~~~~~~~~~~~~~~~~~~~~~~~~~
191 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
193 We will need an instance decl like:
195 instance (Read a, RealFloat a) => Read (Complex a) where
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
202 But this ain't true for Show, Eq, Ord, etc, since they don't construct
203 a Complex; they only take them apart.
205 Our approach: identify the offending classes, and add the data type
206 context to the instance decl. The "offending classes" are
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".
215 Note [Newtype deriving]
216 ~~~~~~~~~~~~~~~~~~~~~~~
220 newtype T = T Char deriving( C [a] )
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] )
225 And then translate it to:
226 instance C [a] Char => C [a] T where ...
229 Note [Newtype deriving superclasses]
230 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
231 (See also Trac #1220 for an interesting exchange on newtype
232 deriving and superclasses.)
234 The 'tys' here come from the partial application in the deriving
235 clause. The last arg is the new instance type.
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
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
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
255 %************************************************************************
257 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
259 %************************************************************************
262 tcDeriving :: [LTyClDecl Name] -- All type constructors
263 -> [LInstDecl Name] -- All instance declarations
264 -> [LDerivDecl Name] -- All stand-alone deriving declarations
265 -> TcM ([InstInfo Name], -- The generated "instance decls"
266 HsValBinds Name) -- Extra generated top-level bindings
268 tcDeriving tycl_decls inst_decls deriv_decls
269 = recoverM (return ([], emptyValBindsOut)) $
270 do { -- Fish the "deriving"-related information out of the TcEnv
271 -- And make the necessary "equations".
272 is_boot <- tcIsHsBoot
273 ; traceTc (text "tcDeriving" <+> ppr is_boot)
274 ; early_specs <- makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
276 ; overlap_flag <- getOverlapFlag
277 ; let (infer_specs, given_specs) = splitEithers early_specs
278 ; insts1 <- mapM (genInst overlap_flag) given_specs
280 ; final_specs <- extendLocalInstEnv (map (iSpec . fst) insts1) $
281 inferInstanceContexts overlap_flag infer_specs
283 ; insts2 <- mapM (genInst overlap_flag) final_specs
285 -- Generate the generic to/from functions from each type declaration
286 ; gen_binds <- mkGenericBinds is_boot
287 ; (inst_info, rn_binds) <- renameDeriv is_boot gen_binds (insts1 ++ insts2)
290 ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
291 (ddump_deriving inst_info rn_binds))
293 ; return (inst_info, rn_binds) }
295 ddump_deriving :: [InstInfo Name] -> HsValBinds Name -> SDoc
296 ddump_deriving inst_infos extra_binds
297 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
299 renameDeriv :: Bool -> LHsBinds RdrName
300 -> [(InstInfo RdrName, DerivAuxBinds)]
301 -> TcM ([InstInfo Name], HsValBinds Name)
302 renameDeriv is_boot gen_binds insts
303 | is_boot -- If we are compiling a hs-boot file, don't generate any derived bindings
304 -- The inst-info bindings will all be empty, but it's easier to
305 -- just use rn_inst_info to change the type appropriately
306 = do { rn_inst_infos <- mapM rn_inst_info inst_infos
307 ; return (rn_inst_infos, emptyValBindsOut) }
310 = discardWarnings $ -- Discard warnings about unused bindings etc
311 do { (rn_gen, dus_gen) <- setOptM Opt_PatternSignatures $ -- Type signatures in patterns
312 -- are used in the generic binds
313 rnTopBinds (ValBindsIn gen_binds [])
314 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to be kept alive
316 -- Generate and rename any extra not-one-inst-decl-specific binds,
317 -- notably "con2tag" and/or "tag2con" functions.
318 -- Bring those names into scope before renaming the instances themselves
319 ; loc <- getSrcSpanM -- Generic loc for shared bindings
320 ; let aux_binds = listToBag $ map (genAuxBind loc) $
321 rm_dups [] $ concat deriv_aux_binds
322 ; rn_aux_lhs <- rnTopBindsLHS emptyFsEnv (ValBindsIn aux_binds [])
323 ; let aux_names = map unLoc (collectHsValBinders rn_aux_lhs)
325 ; bindLocalNames aux_names $
326 do { (rn_aux, _dus) <- rnTopBindsRHS aux_names rn_aux_lhs
327 ; rn_inst_infos <- mapM rn_inst_info inst_infos
328 ; return (rn_inst_infos, rn_aux `plusHsValBinds` rn_gen) } }
331 (inst_infos, deriv_aux_binds) = unzip insts
333 -- Remove duplicate requests for auxilliary bindings
335 rm_dups acc (b:bs) | any (isDupAux b) acc = rm_dups acc bs
336 | otherwise = rm_dups (b:acc) bs
339 rn_inst_info (InstInfo { iSpec = inst, iBinds = NewTypeDerived })
340 = return (InstInfo { iSpec = inst, iBinds = NewTypeDerived })
342 rn_inst_info (InstInfo { iSpec = inst, iBinds = VanillaInst binds sigs })
343 = -- Bring the right type variables into
344 -- scope (yuk), and rename the method binds
346 bindLocalNames (map Var.varName tyvars) $
347 do { (rn_binds, _fvs) <- rnMethodBinds clas_nm (\_ -> []) [] binds
348 ; return (InstInfo { iSpec = inst, iBinds = VanillaInst rn_binds [] }) }
350 (tyvars,_,clas,_) = instanceHead inst
351 clas_nm = className clas
353 -----------------------------------------
354 mkGenericBinds :: Bool -> TcM (LHsBinds RdrName)
355 mkGenericBinds is_boot
359 = do { gbl_env <- getGblEnv
360 ; let tcs = typeEnvTyCons (tcg_type_env gbl_env)
361 ; return (unionManyBags [ mkTyConGenericBinds tc |
362 tc <- tcs, tyConHasGenerics tc ]) }
363 -- We are only interested in the data type declarations,
364 -- and then only in the ones whose 'has-generics' flag is on
365 -- The predicate tyConHasGenerics finds both of these
369 %************************************************************************
371 From HsSyn to DerivSpec
373 %************************************************************************
375 @makeDerivSpecs@ fishes around to find the info about needed derived
376 instances. Complicating factors:
379 We can only derive @Enum@ if the data type is an enumeration
380 type (all nullary data constructors).
383 We can only derive @Ix@ if the data type is an enumeration {\em
384 or} has just one data constructor (e.g., tuples).
387 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
391 makeDerivSpecs :: Bool
395 -> TcM [EarlyDerivSpec]
397 makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
398 | is_boot -- No 'deriving' at all in hs-boot files
399 = do { mapM_ add_deriv_err deriv_locs
402 = do { eqns1 <- mapAndRecoverM deriveTyData all_tydata
403 ; eqns2 <- mapAndRecoverM deriveStandalone deriv_decls
404 ; return (catMaybes (eqns1 ++ eqns2)) }
406 extractTyDataPreds decls
407 = [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
409 all_tydata :: [(LHsType Name, LTyClDecl Name)]
410 -- Derived predicate paired with its data type declaration
411 all_tydata = extractTyDataPreds tycl_decls ++
412 [ pd -- Traverse assoc data families
413 | L _ (InstDecl _ _ _ ats) <- inst_decls
414 , pd <- extractTyDataPreds ats ]
416 deriv_locs = map (getLoc . snd) all_tydata
417 ++ map getLoc deriv_decls
419 add_deriv_err loc = setSrcSpan loc $
420 addErr (hang (ptext (sLit "Deriving not permitted in hs-boot file"))
421 2 (ptext (sLit "Use an instance declaration instead")))
423 ------------------------------------------------------------------
424 deriveStandalone :: LDerivDecl Name -> TcM (Maybe EarlyDerivSpec)
425 -- Standalone deriving declarations
426 -- e.g. deriving instance show a => Show (T a)
427 -- Rather like tcLocalInstDecl
428 deriveStandalone (L loc (DerivDecl deriv_ty))
430 addErrCtxt (standaloneCtxt deriv_ty) $
431 do { traceTc (text "standalone deriving decl for" <+> ppr deriv_ty)
432 ; (tvs, theta, tau) <- tcHsInstHead deriv_ty
433 ; traceTc (text "standalone deriving;"
434 <+> text "tvs:" <+> ppr tvs
435 <+> text "theta:" <+> ppr theta
436 <+> text "tau:" <+> ppr tau)
437 ; (cls, inst_tys) <- checkValidInstHead tau
438 ; checkValidInstance tvs theta cls inst_tys
439 -- C.f. TcInstDcls.tcLocalInstDecl1
441 ; let cls_tys = take (length inst_tys - 1) inst_tys
442 inst_ty = last inst_tys
443 ; traceTc (text "standalone deriving;"
444 <+> text "class:" <+> ppr cls
445 <+> text "class types:" <+> ppr cls_tys
446 <+> text "type:" <+> ppr inst_ty)
447 ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
450 ------------------------------------------------------------------
451 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM (Maybe EarlyDerivSpec)
452 deriveTyData (L loc deriv_pred, L _ decl@(TyData { tcdLName = L _ tycon_name,
453 tcdTyVars = tv_names,
454 tcdTyPats = ty_pats }))
455 = setSrcSpan loc $ -- Use the location of the 'deriving' item
457 do { let hs_ty_args = ty_pats `orElse` map (nlHsTyVar . hsLTyVarName) tv_names
458 hs_app = nlHsTyConApp tycon_name hs_ty_args
459 -- We get kinding info for the tyvars by typechecking (T a b)
460 -- Hence forming a tycon application and then dis-assembling it
461 ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
462 ; tcExtendTyVarEnv tvs $ -- Deriving preds may (now) mention
463 -- the type variables for the type constructor
464 do { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
465 -- The "deriv_pred" is a LHsType to take account of the fact that for
466 -- newtype deriving we allow deriving (forall a. C [a]).
467 ; mkEqnHelp DerivOrigin (tvs++deriv_tvs) cls cls_tys tc_app Nothing } }
470 = panic "derivTyData" -- Caller ensures that only TyData can happen
472 ------------------------------------------------------------------
473 mkEqnHelp :: InstOrigin -> [TyVar] -> Class -> [Type] -> Type
474 -> Maybe ThetaType -- Just => context supplied (standalone deriving)
475 -- Nothing => context inferred (deriving on data decl)
476 -> TcRn (Maybe EarlyDerivSpec)
477 mkEqnHelp orig tvs cls cls_tys tc_app mtheta
478 | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
479 , isAlgTyCon tycon -- Check for functions, primitive types etc
480 = do { (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon tc_args
481 -- Be careful to test rep_tc here: in the case of families,
482 -- we want to check the instance tycon, not the family tycon
484 -- For standalone deriving (mtheta /= Nothing),
485 -- check that all the data constructors are in scope.
486 -- No need for this when deriving Typeable, becuase we don't need
487 -- the constructors for that.
488 -- By this time we know that the thing is algebraic
489 -- because we've called checkInstHead in derivingStandalone
490 ; rdr_env <- getGlobalRdrEnv
491 ; let hidden_data_cons = isAbstractTyCon rep_tc || any not_in_scope (tyConDataCons rep_tc)
492 not_in_scope dc = null (lookupGRE_Name rdr_env (dataConName dc))
493 ; checkTc (isNothing mtheta ||
494 not hidden_data_cons ||
495 className cls `elem` typeableClassNames)
496 (derivingHiddenErr tycon)
498 ; mayDeriveDataTypeable <- doptM Opt_DeriveDataTypeable
499 ; newtype_deriving <- doptM Opt_GeneralizedNewtypeDeriving
501 ; if isDataTyCon rep_tc then
502 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
503 tycon tc_args rep_tc rep_tc_args mtheta
505 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving
507 tycon tc_args rep_tc rep_tc_args mtheta }
509 = baleOut (derivingThingErr cls cls_tys tc_app
510 (ptext (sLit "The last argument of the instance must be a data or newtype application")))
512 baleOut :: Message -> TcM (Maybe a)
513 baleOut err = do { addErrTc err; return Nothing }
516 Note [Looking up family instances for deriving]
517 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
518 tcLookupFamInstExact is an auxiliary lookup wrapper which requires
519 that looked-up family instances exist. If called with a vanilla
520 tycon, the old type application is simply returned.
523 data instance F () = ... deriving Eq
524 data instance F () = ... deriving Eq
525 then tcLookupFamInstExact will be confused by the two matches;
526 but that can't happen because tcInstDecls1 doesn't call tcDeriving
527 if there are any overlaps.
529 There are two other things that might go wrong with the lookup.
530 First, we might see a standalone deriving clause
532 when there is no data instance F () in scope.
534 Note that it's OK to have
535 data instance F [a] = ...
536 deriving Eq (F [(a,b)])
537 where the match is not exact; the same holds for ordinary data types
538 with standalone deriving declrations.
541 tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
542 tcLookupFamInstExact tycon tys
543 | not (isOpenTyCon tycon)
544 = return (tycon, tys)
546 = do { maybeFamInst <- tcLookupFamInst tycon tys
547 ; case maybeFamInst of
548 Nothing -> famInstNotFound tycon tys
549 Just famInst -> return famInst
552 famInstNotFound :: TyCon -> [Type] -> TcM a
553 famInstNotFound tycon tys
554 = failWithTc (ptext (sLit "No family instance for")
555 <+> quotes (pprTypeApp tycon tys))
559 %************************************************************************
563 %************************************************************************
566 mkDataTypeEqn :: InstOrigin -> Bool -> [Var] -> Class -> [Type]
567 -> TyCon -> [Type] -> TyCon -> [Type] -> Maybe ThetaType
568 -> TcRn (Maybe EarlyDerivSpec) -- Return 'Nothing' if error
570 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
571 tycon tc_args rep_tc rep_tc_args mtheta
572 | Just err <- checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
573 -- NB: pass the *representation* tycon to checkSideConditions
574 = baleOut (derivingThingErr cls cls_tys (mkTyConApp tycon tc_args) err)
577 = ASSERT( null cls_tys )
578 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
580 mk_data_eqn, mk_typeable_eqn
581 :: InstOrigin -> [TyVar] -> Class
582 -> TyCon -> [TcType] -> TyCon -> [TcType] -> Maybe ThetaType
583 -> TcM (Maybe EarlyDerivSpec)
584 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
585 | getName cls `elem` typeableClassNames
586 = mk_typeable_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
589 = do { dfun_name <- new_dfun_name cls tycon
591 ; let ordinary_constraints
592 = [ mkClassPred cls [arg_ty]
593 | data_con <- tyConDataCons rep_tc,
594 arg_ty <- ASSERT( isVanillaDataCon data_con )
595 dataConInstOrigArgTys data_con rep_tc_args,
596 not (isUnLiftedType arg_ty) ] -- No constraints for unlifted types?
598 -- See Note [Superclasses of derived instance]
599 sc_constraints = substTheta (zipOpenTvSubst (classTyVars cls) inst_tys)
601 inst_tys = [mkTyConApp tycon tc_args]
603 stupid_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
604 stupid_constraints = substTheta stupid_subst (tyConStupidTheta rep_tc)
605 all_constraints = stupid_constraints ++ sc_constraints ++ ordinary_constraints
607 spec = DS { ds_loc = loc, ds_orig = orig
608 , ds_name = dfun_name, ds_tvs = tvs
609 , ds_cls = cls, ds_tys = inst_tys
610 , ds_theta = mtheta `orElse` all_constraints
611 , ds_newtype = False }
613 ; return (if isJust mtheta then Just (Right spec) -- Specified context
614 else Just (Left spec)) } -- Infer context
616 mk_typeable_eqn orig tvs cls tycon tc_args rep_tc _rep_tc_args mtheta
617 -- The Typeable class is special in several ways
618 -- data T a b = ... deriving( Typeable )
620 -- instance Typeable2 T where ...
622 -- 1. There are no constraints in the instance
623 -- 2. There are no type variables either
624 -- 3. The actual class we want to generate isn't necessarily
625 -- Typeable; it depends on the arity of the type
626 | isNothing mtheta -- deriving on a data type decl
627 = do { checkTc (cls `hasKey` typeableClassKey)
628 (ptext (sLit "Use deriving( Typeable ) on a data type declaration"))
629 ; real_cls <- tcLookupClass (typeableClassNames !! tyConArity tycon)
630 ; mk_typeable_eqn orig tvs real_cls tycon [] rep_tc [] (Just []) }
632 | otherwise -- standaone deriving
633 = do { checkTc (null tc_args)
634 (ptext (sLit "Derived typeable instance must be of form (Typeable")
635 <> int (tyConArity tycon) <+> ppr tycon <> rparen)
636 ; dfun_name <- new_dfun_name cls tycon
638 ; return (Just $ Right $
639 DS { ds_loc = loc, ds_orig = orig, ds_name = dfun_name, ds_tvs = []
640 , ds_cls = cls, ds_tys = [mkTyConApp tycon []]
641 , ds_theta = mtheta `orElse` [], ds_newtype = False }) }
643 ------------------------------------------------------------------
644 -- Check side conditions that dis-allow derivability for particular classes
645 -- This is *apart* from the newtype-deriving mechanism
647 -- Here we get the representation tycon in case of family instances as it has
648 -- the data constructors - but we need to be careful to fall back to the
649 -- family tycon (with indexes) in error messages.
651 checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> Maybe SDoc
652 checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
654 = Just ty_args_why -- e.g. deriving( Foo s )
656 = case sideConditions cls of
657 Just cond -> cond (mayDeriveDataTypeable, rep_tc)
658 Nothing -> Just non_std_why
660 ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "is not a class")
661 non_std_why = quotes (ppr cls) <+> ptext (sLit "is not a derivable class")
663 sideConditions :: Class -> Maybe Condition
665 | cls_key == eqClassKey = Just cond_std
666 | cls_key == ordClassKey = Just cond_std
667 | cls_key == readClassKey = Just cond_std
668 | cls_key == showClassKey = Just cond_std
669 | cls_key == enumClassKey = Just (cond_std `andCond` cond_isEnumeration)
670 | cls_key == ixClassKey = Just (cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct))
671 | cls_key == boundedClassKey = Just (cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct))
672 | cls_key == dataClassKey = Just (cond_mayDeriveDataTypeable `andCond` cond_std)
673 | getName cls `elem` typeableClassNames = Just (cond_mayDeriveDataTypeable `andCond` cond_typeableOK)
674 | otherwise = Nothing
676 cls_key = getUnique cls
678 type Condition = (Bool, TyCon) -> Maybe SDoc
679 -- Bool is whether or not we are allowed to derive Data and Typeable
680 -- TyCon is the *representation* tycon if the
681 -- data type is an indexed one
684 orCond :: Condition -> Condition -> Condition
687 Nothing -> Nothing -- c1 succeeds
688 Just x -> case c2 tc of -- c1 fails
690 Just y -> Just (x $$ ptext (sLit " and") $$ y)
693 andCond :: Condition -> Condition -> Condition
694 andCond c1 c2 tc = case c1 tc of
695 Nothing -> c2 tc -- c1 succeeds
696 Just x -> Just x -- c1 fails
698 cond_std :: Condition
700 | any (not . isVanillaDataCon) data_cons = Just existential_why
701 | null data_cons = Just no_cons_why
702 | otherwise = Nothing
704 data_cons = tyConDataCons rep_tc
705 no_cons_why = quotes (pprSourceTyCon rep_tc) <+>
706 ptext (sLit "has no data constructors")
707 existential_why = quotes (pprSourceTyCon rep_tc) <+>
708 ptext (sLit "has non-Haskell-98 constructor(s)")
710 cond_isEnumeration :: Condition
711 cond_isEnumeration (_, rep_tc)
712 | isEnumerationTyCon rep_tc = Nothing
713 | otherwise = Just why
715 why = quotes (pprSourceTyCon rep_tc) <+>
716 ptext (sLit "has non-nullary constructors")
718 cond_isProduct :: Condition
719 cond_isProduct (_, rep_tc)
720 | isProductTyCon rep_tc = Nothing
721 | otherwise = Just why
723 why = quotes (pprSourceTyCon rep_tc) <+>
724 ptext (sLit "has more than one constructor")
726 cond_typeableOK :: Condition
727 -- OK for Typeable class
728 -- Currently: (a) args all of kind *
729 -- (b) 7 or fewer args
730 cond_typeableOK (_, rep_tc)
731 | tyConArity rep_tc > 7 = Just too_many
732 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc))
734 | isFamInstTyCon rep_tc = Just fam_inst -- no Typable for family insts
735 | otherwise = Nothing
737 too_many = quotes (pprSourceTyCon rep_tc) <+>
738 ptext (sLit "has too many arguments")
739 bad_kind = quotes (pprSourceTyCon rep_tc) <+>
740 ptext (sLit "has arguments of kind other than `*'")
741 fam_inst = quotes (pprSourceTyCon rep_tc) <+>
742 ptext (sLit "is a type family")
744 cond_mayDeriveDataTypeable :: Condition
745 cond_mayDeriveDataTypeable (mayDeriveDataTypeable, _)
746 | mayDeriveDataTypeable = Nothing
747 | otherwise = Just why
749 why = ptext (sLit "You need -XDeriveDataTypeable to derive an instance for this class")
751 std_class_via_iso :: Class -> Bool
752 std_class_via_iso clas -- These standard classes can be derived for a newtype
753 -- using the isomorphism trick *even if no -fglasgow-exts*
754 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
755 -- Not Read/Show because they respect the type
756 -- Not Enum, because newtypes are never in Enum
759 new_dfun_name :: Class -> TyCon -> TcM Name
760 new_dfun_name clas tycon -- Just a simple wrapper
761 = do { loc <- getSrcSpanM -- The location of the instance decl, not of the tycon
762 ; newDFunName clas [mkTyConApp tycon []] loc }
763 -- The type passed to newDFunName is only used to generate
764 -- a suitable string; hence the empty type arg list
767 Note [Superclasses of derived instance]
768 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
769 In general, a derived instance decl needs the superclasses of the derived
770 class too. So if we have
771 data T a = ...deriving( Ord )
772 then the initial context for Ord (T a) should include Eq (T a). Often this is
773 redundant; we'll also generate an Ord constraint for each constructor argument,
774 and that will probably generate enough constraints to make the Eq (T a) constraint
775 be satisfied too. But not always; consider:
781 data T a = MkT (S a) deriving( Ord )
782 instance Num a => Eq (T a)
784 The derived instance for (Ord (T a)) must have a (Num a) constraint!
786 data T a = MkT deriving( Data, Typeable )
787 Here there *is* no argument field, but we must nevertheless generate
788 a context for the Data instances:
789 instance Typable a => Data (T a) where ...
792 %************************************************************************
796 %************************************************************************
799 mkNewTypeEqn :: InstOrigin -> Bool -> Bool -> [Var] -> Class
800 -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
802 -> TcRn (Maybe EarlyDerivSpec)
803 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving tvs
804 cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
805 | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
806 = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
807 ; dfun_name <- new_dfun_name cls tycon
809 ; let spec = DS { ds_loc = loc, ds_orig = orig
810 , ds_name = dfun_name, ds_tvs = dict_tvs
811 , ds_cls = cls, ds_tys = inst_tys
812 , ds_theta = mtheta `orElse` all_preds
813 , ds_newtype = True }
814 ; return (if isJust mtheta then Just (Right spec)
815 else Just (Left spec)) }
817 | isNothing mb_std_err -- Use the standard H98 method
818 = mk_data_eqn orig tvs cls tycon tc_args rep_tycon rep_tc_args mtheta
820 -- Otherwise we can't derive
821 | newtype_deriving = baleOut cant_derive_err -- Too hard
822 | otherwise = baleOut std_err -- Just complain about being a non-std instance
824 mb_std_err = checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tycon
825 std_err = derivingThingErr cls cls_tys tc_app $
826 vcat [fromJust mb_std_err,
827 ptext (sLit "Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")]
829 -- Here is the plan for newtype derivings. We see
830 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
831 -- where t is a type,
832 -- ak+1...an is a suffix of a1..an, and are all tyars
833 -- ak+1...an do not occur free in t, nor in the s1..sm
834 -- (C s1 ... sm) is a *partial applications* of class C
835 -- with the last parameter missing
836 -- (T a1 .. ak) matches the kind of C's last argument
837 -- (and hence so does t)
839 -- We generate the instance
840 -- instance forall ({a1..ak} u fvs(s1..sm)).
841 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
842 -- where T a1...ap is the partial application of
843 -- the LHS of the correct kind and p >= k
845 -- NB: the variables below are:
846 -- tc_tvs = [a1, ..., an]
847 -- tyvars_to_keep = [a1, ..., ak]
848 -- rep_ty = t ak .. an
849 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
850 -- tys = [s1, ..., sm]
853 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
854 -- We generate the instance
855 -- instance Monad (ST s) => Monad (T s) where
857 cls_tyvars = classTyVars cls
858 kind = tyVarKind (last cls_tyvars)
859 -- Kind of the thing we want to instance
860 -- e.g. argument kind of Monad, *->*
862 (arg_kinds, _) = splitKindFunTys kind
863 n_args_to_drop = length arg_kinds
864 -- Want to drop 1 arg from (T s a) and (ST s a)
865 -- to get instance Monad (ST s) => Monad (T s)
867 -- Note [Newtype representation]
868 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
869 -- Need newTyConRhs (*not* a recursive representation finder)
870 -- to get the representation type. For example
871 -- newtype B = MkB Int
872 -- newtype A = MkA B deriving( Num )
873 -- We want the Num instance of B, *not* the Num instance of Int,
874 -- when making the Num instance of A!
875 rep_ty = newTyConInstRhs rep_tycon rep_tc_args
876 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
878 n_tyargs_to_keep = tyConArity tycon - n_args_to_drop
879 dropped_tc_args = drop n_tyargs_to_keep tc_args
880 dropped_tvs = tyVarsOfTypes dropped_tc_args
882 n_args_to_keep = length rep_ty_args - n_args_to_drop
883 args_to_drop = drop n_args_to_keep rep_ty_args
884 args_to_keep = take n_args_to_keep rep_ty_args
886 rep_fn' = mkAppTys rep_fn args_to_keep
887 rep_tys = cls_tys ++ [rep_fn']
888 rep_pred = mkClassPred cls rep_tys
889 -- rep_pred is the representation dictionary, from where
890 -- we are gong to get all the methods for the newtype
893 tc_app = mkTyConApp tycon (take n_tyargs_to_keep tc_args)
895 -- Next we figure out what superclass dictionaries to use
896 -- See Note [Newtype deriving superclasses] above
898 inst_tys = cls_tys ++ [tc_app]
899 sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
902 -- If there are no tyvars, there's no need
903 -- to abstract over the dictionaries we need
904 -- Example: newtype T = MkT Int deriving( C )
905 -- We get the derived instance
908 -- instance C Int => C T
909 dict_tvs = filterOut (`elemVarSet` dropped_tvs) tvs
910 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
912 -------------------------------------------------------------------
913 -- Figuring out whether we can only do this newtype-deriving thing
915 right_arity = length cls_tys + 1 == classArity cls
917 -- Never derive Read,Show,Typeable,Data this way
918 non_iso_class cls = className cls `elem` ([readClassName, showClassName, dataClassName] ++
920 can_derive_via_isomorphism
921 = not (non_iso_class cls)
922 && right_arity -- Well kinded;
923 -- eg not: newtype T ... deriving( ST )
924 -- because ST needs *2* type params
925 && n_tyargs_to_keep >= 0 -- Type constructor has right kind:
926 -- eg not: newtype T = T Int deriving( Monad )
927 && n_args_to_keep >= 0 -- Rep type has right kind:
928 -- eg not: newtype T a = T Int deriving( Monad )
929 && eta_ok -- Eta reduction works
930 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
931 -- newtype A = MkA [A]
933 -- instance Eq [A] => Eq A !!
934 -- Here's a recursive newtype that's actually OK
935 -- newtype S1 = S1 [T1 ()]
936 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
937 -- It's currently rejected. Oh well.
938 -- In fact we generate an instance decl that has method of form
939 -- meth @ instTy = meth @ repTy
940 -- (no coerce's). We'd need a coerce if we wanted to handle
941 -- recursive newtypes too
943 -- Check that eta reduction is OK
944 eta_ok = (args_to_drop `tcEqTypes` dropped_tc_args)
945 -- (a) the dropped-off args are identical in the source and rep type
946 -- newtype T a b = MkT (S [a] b) deriving( Monad )
947 -- Here the 'b' must be the same in the rep type (S [a] b)
949 && (tyVarsOfType rep_fn' `disjointVarSet` dropped_tvs)
950 -- (b) the remaining type args do not mention any of the dropped
953 && (tyVarsOfTypes cls_tys `disjointVarSet` dropped_tvs)
954 -- (c) the type class args do not mention any of the dropped type
957 && all isTyVarTy dropped_tc_args
958 -- (d) in case of newtype family instances, the eta-dropped
959 -- arguments must be type variables (not more complex indexes)
961 cant_derive_err = derivingThingErr cls cls_tys tc_app
962 (vcat [ptext (sLit "even with cunning newtype deriving:"),
963 if isRecursiveTyCon tycon then
964 ptext (sLit "the newtype may be recursive")
966 if not right_arity then
967 quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "does not have arity 1")
969 if not (n_tyargs_to_keep >= 0) then
970 ptext (sLit "the type constructor has wrong kind")
971 else if not (n_args_to_keep >= 0) then
972 ptext (sLit "the representation type has wrong kind")
973 else if not eta_ok then
974 ptext (sLit "the eta-reduction property does not hold")
980 %************************************************************************
982 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
984 %************************************************************************
986 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
987 terms, which is the final correct RHS for the corresponding original
991 Each (k,TyVarTy tv) in a solution constrains only a type
995 The (k,TyVarTy tv) pairs in a solution are canonically
996 ordered by sorting on type varible, tv, (major key) and then class, k,
1001 inferInstanceContexts :: OverlapFlag -> [DerivSpec] -> TcM [DerivSpec]
1003 inferInstanceContexts _ [] = return []
1005 inferInstanceContexts oflag infer_specs
1006 = do { traceTc (text "inferInstanceContexts" <+> vcat (map pprDerivSpec infer_specs))
1007 ; iterate_deriv 1 initial_solutions }
1009 ------------------------------------------------------------------
1010 -- The initial solutions for the equations claim that each
1011 -- instance has an empty context; this solution is certainly
1012 -- in canonical form.
1013 initial_solutions :: [ThetaType]
1014 initial_solutions = [ [] | _ <- infer_specs ]
1016 ------------------------------------------------------------------
1017 -- iterate_deriv calculates the next batch of solutions,
1018 -- compares it with the current one; finishes if they are the
1019 -- same, otherwise recurses with the new solutions.
1020 -- It fails if any iteration fails
1021 iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec]
1022 iterate_deriv n current_solns
1023 | n > 20 -- Looks as if we are in an infinite loop
1024 -- This can happen if we have -XUndecidableInstances
1025 -- (See TcSimplify.tcSimplifyDeriv.)
1026 = pprPanic "solveDerivEqns: probable loop"
1027 (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
1029 = do { -- Extend the inst info from the explicit instance decls
1030 -- with the current set of solutions, and simplify each RHS
1031 let inst_specs = zipWithEqual "add_solns" (mkInstance2 oflag)
1032 current_solns infer_specs
1033 ; new_solns <- checkNoErrs $
1034 extendLocalInstEnv inst_specs $
1035 mapM gen_soln infer_specs
1037 ; if (current_solns == new_solns) then
1038 return [ spec { ds_theta = soln }
1039 | (spec, soln) <- zip infer_specs current_solns ]
1041 iterate_deriv (n+1) new_solns }
1043 ------------------------------------------------------------------
1044 gen_soln :: DerivSpec -> TcM [PredType]
1045 gen_soln (DS { ds_loc = loc, ds_orig = orig, ds_tvs = tyvars
1046 , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
1048 addErrCtxt (derivInstCtxt clas inst_tys) $
1049 do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
1050 -- checkValidInstance tyvars theta clas inst_tys
1051 -- Not necessary; see Note [Exotic derived instance contexts]
1054 -- Check for a bizarre corner case, when the derived instance decl should
1055 -- have form instance C a b => D (T a) where ...
1056 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
1057 -- of problems; in particular, it's hard to compare solutions for
1058 -- equality when finding the fixpoint. So I just rule it out for now.
1059 ; let tv_set = mkVarSet tyvars
1060 weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]
1061 ; mapM_ (addErrTc . badDerivedPred) weird_preds
1063 -- Claim: the result instance declaration is guaranteed valid
1064 -- Hence no need to call:
1065 -- checkValidInstance tyvars theta clas inst_tys
1066 ; return (sortLe (<=) theta) } -- Canonicalise before returning the solution
1068 ------------------------------------------------------------------
1069 mkInstance1 :: OverlapFlag -> DerivSpec -> Instance
1070 mkInstance1 overlap_flag spec = mkInstance2 overlap_flag (ds_theta spec) spec
1072 mkInstance2 :: OverlapFlag -> ThetaType -> DerivSpec -> Instance
1073 mkInstance2 overlap_flag theta
1074 (DS { ds_name = dfun_name
1075 , ds_tvs = tyvars, ds_cls = clas, ds_tys = tys })
1076 = mkLocalInstance dfun overlap_flag
1078 dfun = mkDictFunId dfun_name tyvars theta clas tys
1081 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
1082 -- Add new locally-defined instances; don't bother to check
1083 -- for functional dependency errors -- that'll happen in TcInstDcls
1084 extendLocalInstEnv dfuns thing_inside
1085 = do { env <- getGblEnv
1086 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
1087 env' = env { tcg_inst_env = inst_env' }
1088 ; setGblEnv env' thing_inside }
1092 %************************************************************************
1094 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
1096 %************************************************************************
1098 After all the trouble to figure out the required context for the
1099 derived instance declarations, all that's left is to chug along to
1100 produce them. They will then be shoved into @tcInstDecls2@, which
1101 will do all its usual business.
1103 There are lots of possibilities for code to generate. Here are
1104 various general remarks.
1109 We want derived instances of @Eq@ and @Ord@ (both v common) to be
1110 ``you-couldn't-do-better-by-hand'' efficient.
1113 Deriving @Show@---also pretty common--- should also be reasonable good code.
1116 Deriving for the other classes isn't that common or that big a deal.
1123 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
1126 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
1129 We {\em normally} generate code only for the non-defaulted methods;
1130 there are some exceptions for @Eq@ and (especially) @Ord@...
1133 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
1134 constructor's numeric (@Int#@) tag. These are generated by
1135 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
1136 these is around is given by @hasCon2TagFun@.
1138 The examples under the different sections below will make this
1142 Much less often (really just for deriving @Ix@), we use a
1143 @_tag2con_<tycon>@ function. See the examples.
1146 We use the renamer!!! Reason: we're supposed to be
1147 producing @LHsBinds Name@ for the methods, but that means
1148 producing correctly-uniquified code on the fly. This is entirely
1149 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
1150 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
1151 the renamer. What a great hack!
1155 -- Generate the InstInfo for the required instance paired with the
1156 -- *representation* tycon for that instance,
1157 -- plus any auxiliary bindings required
1159 -- Representation tycons differ from the tycon in the instance signature in
1160 -- case of instances for indexed families.
1162 genInst :: OverlapFlag -> DerivSpec -> TcM (InstInfo RdrName, DerivAuxBinds)
1165 = return (InstInfo { iSpec = mkInstance1 oflag spec
1166 , iBinds = NewTypeDerived }, [])
1169 = do { let loc = getSrcSpan (ds_name spec)
1170 inst = mkInstance1 oflag spec
1171 (_,_,clas,[ty]) = instanceHead inst
1172 (visible_tycon, tyArgs) = tcSplitTyConApp ty
1174 -- In case of a family instance, we need to use the representation
1175 -- tycon (after all, it has the data constructors)
1176 ; (tycon, _) <- tcLookupFamInstExact visible_tycon tyArgs
1177 ; fix_env <- getFixityEnv
1178 ; let (meth_binds, aux_binds) = genDerivBinds loc fix_env clas tycon
1180 -- Build the InstInfo
1181 ; return (InstInfo { iSpec = inst,
1182 iBinds = VanillaInst meth_binds [] },
1186 genDerivBinds :: SrcSpan -> FixityEnv -> Class -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1187 genDerivBinds loc fix_env clas tycon
1188 | className clas `elem` typeableClassNames
1189 = (gen_Typeable_binds loc tycon, [])
1192 = case assocMaybe gen_list (getUnique clas) of
1193 Just gen_fn -> gen_fn loc tycon
1194 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1196 gen_list :: [(Unique, SrcSpan -> TyCon -> (LHsBinds RdrName, DerivAuxBinds))]
1197 gen_list = [(eqClassKey, gen_Eq_binds)
1198 ,(ordClassKey, gen_Ord_binds)
1199 ,(enumClassKey, gen_Enum_binds)
1200 ,(boundedClassKey, gen_Bounded_binds)
1201 ,(ixClassKey, gen_Ix_binds)
1202 ,(showClassKey, gen_Show_binds fix_env)
1203 ,(readClassKey, gen_Read_binds fix_env)
1204 ,(dataClassKey, gen_Data_binds)
1209 %************************************************************************
1211 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1213 %************************************************************************
1216 derivingThingErr :: Class -> [Type] -> Type -> Message -> Message
1217 derivingThingErr clas tys ty why
1218 = sep [hsep [ptext (sLit "Can't make a derived instance of"),
1220 nest 2 (parens why)]
1222 pred = mkClassPred clas (tys ++ [ty])
1224 derivingHiddenErr :: TyCon -> SDoc
1225 derivingHiddenErr tc
1226 = hang (ptext (sLit "The data constructors of") <+> quotes (ppr tc) <+> ptext (sLit "are not all in scope"))
1227 2 (ptext (sLit "so you cannot derive an instance for it"))
1229 standaloneCtxt :: LHsType Name -> SDoc
1230 standaloneCtxt ty = hang (ptext (sLit "In the stand-alone deriving instance for"))
1233 derivInstCtxt :: Class -> [Type] -> Message
1234 derivInstCtxt clas inst_tys
1235 = ptext (sLit "When deriving the instance for") <+> parens (pprClassPred clas inst_tys)
1237 badDerivedPred :: PredType -> Message
1239 = vcat [ptext (sLit "Can't derive instances where the instance context mentions"),
1240 ptext (sLit "type variables that are not data type parameters"),
1241 nest 2 (ptext (sLit "Offending constraint:") <+> ppr pred)]