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
52 %************************************************************************
56 %************************************************************************
60 1. Convert the decls (i.e. data/newtype deriving clauses,
61 plus standalone deriving) to [EarlyDerivSpec]
63 2. Infer the missing contexts for the Left DerivSpecs
65 3. Add the derived bindings, generating InstInfos
68 -- DerivSpec is purely local to this module
69 data DerivSpec = DS { ds_loc :: SrcSpan
70 , ds_orig :: InstOrigin
73 , ds_theta :: ThetaType
76 , ds_newtype :: Bool }
77 -- This spec implies a dfun declaration of the form
78 -- df :: forall tvs. theta => C tys
79 -- The Name is the name for the DFun we'll build
80 -- The tyvars bind all the variables in the theta
81 -- For family indexes, the tycon is the *family* tycon
82 -- (not the representation tycon)
84 -- ds_newtype = True <=> Newtype deriving
85 -- False <=> Vanilla deriving
87 type EarlyDerivSpec = Either DerivSpec DerivSpec
88 -- Left ds => the context for the instance should be inferred
89 -- (ds_theta is required)
90 -- Right ds => the context for the instance is supplied by the programmer
92 pprDerivSpec :: DerivSpec -> SDoc
93 pprDerivSpec (DS { ds_loc = l, ds_name = n, ds_tvs = tvs,
94 ds_cls = c, ds_tys = tys, ds_theta = rhs })
95 = parens (hsep [ppr l, ppr n, ppr tvs, ppr c, ppr tys]
96 <+> equals <+> ppr rhs)
100 Inferring missing contexts
101 ~~~~~~~~~~~~~~~~~~~~~~~~~~
104 data T a b = C1 (Foo a) (Bar b)
109 [NOTE: See end of these comments for what to do with
110 data (C a, D b) => T a b = ...
113 We want to come up with an instance declaration of the form
115 instance (Ping a, Pong b, ...) => Eq (T a b) where
118 It is pretty easy, albeit tedious, to fill in the code "...". The
119 trick is to figure out what the context for the instance decl is,
120 namely @Ping@, @Pong@ and friends.
122 Let's call the context reqd for the T instance of class C at types
123 (a,b, ...) C (T a b). Thus:
125 Eq (T a b) = (Ping a, Pong b, ...)
127 Now we can get a (recursive) equation from the @data@ decl:
129 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
130 u Eq (T b a) u Eq Int -- From C2
131 u Eq (T a a) -- From C3
133 Foo and Bar may have explicit instances for @Eq@, in which case we can
134 just substitute for them. Alternatively, either or both may have
135 their @Eq@ instances given by @deriving@ clauses, in which case they
136 form part of the system of equations.
138 Now all we need do is simplify and solve the equations, iterating to
139 find the least fixpoint. Notice that the order of the arguments can
140 switch around, as here in the recursive calls to T.
142 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
146 Eq (T a b) = {} -- The empty set
149 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
150 u Eq (T b a) u Eq Int -- From C2
151 u Eq (T a a) -- From C3
153 After simplification:
154 = Eq a u Ping b u {} u {} u {}
159 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
160 u Eq (T b a) u Eq Int -- From C2
161 u Eq (T a a) -- From C3
163 After simplification:
168 = Eq a u Ping b u Eq b u Ping a
170 The next iteration gives the same result, so this is the fixpoint. We
171 need to make a canonical form of the RHS to ensure convergence. We do
172 this by simplifying the RHS to a form in which
174 - the classes constrain only tyvars
175 - the list is sorted by tyvar (major key) and then class (minor key)
176 - no duplicates, of course
178 So, here are the synonyms for the ``equation'' structures:
181 Note [Data decl contexts]
182 ~~~~~~~~~~~~~~~~~~~~~~~~~
185 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
187 We will need an instance decl like:
189 instance (Read a, RealFloat a) => Read (Complex a) where
192 The RealFloat in the context is because the read method for Complex is bound
193 to construct a Complex, and doing that requires that the argument type is
196 But this ain't true for Show, Eq, Ord, etc, since they don't construct
197 a Complex; they only take them apart.
199 Our approach: identify the offending classes, and add the data type
200 context to the instance decl. The "offending classes" are
204 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
205 pattern matching against a constructor from a data type with a context
206 gives rise to the constraints for that context -- or at least the thinned
207 version. So now all classes are "offending".
209 Note [Newtype deriving]
210 ~~~~~~~~~~~~~~~~~~~~~~~
214 newtype T = T Char deriving( C [a] )
216 Notice the free 'a' in the deriving. We have to fill this out to
217 newtype T = T Char deriving( forall a. C [a] )
219 And then translate it to:
220 instance C [a] Char => C [a] T where ...
223 Note [Newtype deriving superclasses]
224 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
225 The 'tys' here come from the partial application in the deriving
226 clause. The last arg is the new instance type.
228 We must pass the superclasses; the newtype might be an instance
229 of them in a different way than the representation type
230 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
231 Then the Show instance is not done via isomorphism; it shows
233 The Num instance is derived via isomorphism, but the Show superclass
234 dictionary must the Show instance for Foo, *not* the Show dictionary
235 gotten from the Num dictionary. So we must build a whole new dictionary
236 not just use the Num one. The instance we want is something like:
237 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
240 There may be a coercion needed which we get from the tycon for the newtype
241 when the dict is constructed in TcInstDcls.tcInstDecl2
246 %************************************************************************
248 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
250 %************************************************************************
253 tcDeriving :: [LTyClDecl Name] -- All type constructors
254 -> [LInstDecl Name] -- All instance declarations
255 -> [LDerivDecl Name] -- All stand-alone deriving declarations
256 -> TcM ([InstInfo], -- The generated "instance decls"
257 HsValBinds Name) -- Extra generated top-level bindings
259 tcDeriving tycl_decls inst_decls deriv_decls
260 = recoverM (returnM ([], emptyValBindsOut)) $
261 do { -- Fish the "deriving"-related information out of the TcEnv
262 -- And make the necessary "equations".
263 ; early_specs <- makeDerivSpecs tycl_decls inst_decls deriv_decls
265 ; overlap_flag <- getOverlapFlag
266 ; let (infer_specs, given_specs) = splitEithers early_specs
267 ; (insts1, aux_binds1) <- mapAndUnzipM (genInst overlap_flag) given_specs
269 ; final_specs <- extendLocalInstEnv (map iSpec insts1) $
270 inferInstanceContexts overlap_flag infer_specs
272 ; (insts2, aux_binds2) <- mapAndUnzipM (genInst overlap_flag) final_specs
274 ; is_boot <- tcIsHsBoot
275 ; rn_binds <- makeAuxBinds is_boot tycl_decls
276 (concat aux_binds1 ++ concat aux_binds2)
278 ; let inst_info = insts1 ++ insts2
281 ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
282 (ddump_deriving inst_info rn_binds))
284 ; return (inst_info, rn_binds) }
286 ddump_deriving :: [InstInfo] -> HsValBinds Name -> SDoc
287 ddump_deriving inst_infos extra_binds
288 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
290 makeAuxBinds :: Bool -> [LTyClDecl Name] -> DerivAuxBinds -> TcM (HsValBinds Name)
291 makeAuxBinds is_boot tycl_decls deriv_aux_binds
292 | is_boot -- If we are compiling a hs-boot file,
293 -- don't generate any derived bindings
294 = return emptyValBindsOut
297 = do { let aux_binds = listToBag (map genAuxBind (rm_dups [] deriv_aux_binds))
298 -- Generate any extra not-one-inst-decl-specific binds,
299 -- notably "con2tag" and/or "tag2con" functions.
301 -- Generate the generic to/from functions from each type declaration
302 ; gen_binds <- mkGenericBinds tycl_decls
304 -- Rename these extra bindings, discarding warnings about unused bindings etc
305 -- Type signatures in patterns are used in the generic binds
307 setOptM Opt_PatternSignatures $
308 do { (rn_deriv, _dus1) <- rnTopBinds (ValBindsIn aux_binds [])
309 ; (rn_gen, dus_gen) <- rnTopBinds (ValBindsIn gen_binds [])
310 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to
312 ; return (rn_deriv `plusHsValBinds` rn_gen) } }
314 -- Remove duplicate requests for auxilliary bindings
316 rm_dups acc (b:bs) | any (isDupAux b) acc = rm_dups acc bs
317 | otherwise = rm_dups (b:acc) bs
319 -----------------------------------------
320 mkGenericBinds :: [LTyClDecl Name] -> TcM (LHsBinds RdrName)
321 mkGenericBinds tycl_decls
322 = do { tcs <- mapM tcLookupTyCon
324 L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
325 -- We are only interested in the data type declarations
326 ; return (unionManyBags [ mkTyConGenericBinds tc |
327 tc <- tcs, tyConHasGenerics tc ]) }
328 -- And then only in the ones whose 'has-generics' flag is on
332 %************************************************************************
334 From HsSyn to DerivSpec
336 %************************************************************************
338 @makeDerivSpecs@ fishes around to find the info about needed derived
339 instances. Complicating factors:
342 We can only derive @Enum@ if the data type is an enumeration
343 type (all nullary data constructors).
346 We can only derive @Ix@ if the data type is an enumeration {\em
347 or} has just one data constructor (e.g., tuples).
350 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
354 makeDerivSpecs :: [LTyClDecl Name]
357 -> TcM [EarlyDerivSpec]
359 makeDerivSpecs tycl_decls inst_decls deriv_decls
360 = do { eqns1 <- mapM deriveTyData $
361 extractTyDataPreds tycl_decls ++
362 [ pd -- traverse assoc data families
363 | L _ (InstDecl _ _ _ ats) <- inst_decls
364 , pd <- extractTyDataPreds ats ]
365 ; eqns2 <- mapM deriveStandalone deriv_decls
366 ; return (catMaybes (eqns1 ++ eqns2)) }
368 extractTyDataPreds decls =
369 [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
372 ------------------------------------------------------------------
373 deriveStandalone :: LDerivDecl Name -> TcM (Maybe EarlyDerivSpec)
374 -- Standalone deriving declarations
375 -- e.g. deriving instance show a => Show (T a)
376 -- Rather like tcLocalInstDecl
377 deriveStandalone (L loc (DerivDecl deriv_ty))
379 addErrCtxt (standaloneCtxt deriv_ty) $
380 do { traceTc (text "standalone deriving decl for" <+> ppr deriv_ty)
381 ; (tvs, theta, tau) <- tcHsInstHead deriv_ty
382 ; traceTc (text "standalone deriving;"
383 <+> text "tvs:" <+> ppr tvs
384 <+> text "theta:" <+> ppr theta
385 <+> text "tau:" <+> ppr tau)
386 ; (cls, inst_tys) <- checkValidInstHead tau
387 ; let cls_tys = take (length inst_tys - 1) inst_tys
388 inst_ty = last inst_tys
390 ; traceTc (text "standalone deriving;"
391 <+> text "class:" <+> ppr cls
392 <+> text "class types:" <+> ppr cls_tys
393 <+> text "type:" <+> ppr inst_ty)
394 ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
397 ------------------------------------------------------------------
398 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM (Maybe EarlyDerivSpec)
399 deriveTyData (deriv_pred, L loc decl@(TyData { tcdLName = L _ tycon_name,
400 tcdTyVars = tv_names,
401 tcdTyPats = ty_pats }))
404 do { let hs_ty_args = ty_pats `orElse` map (nlHsTyVar . hsLTyVarName) tv_names
405 hs_app = nlHsTyConApp tycon_name hs_ty_args
406 -- We get kinding info for the tyvars by typechecking (T a b)
407 -- Hence forming a tycon application and then dis-assembling it
408 ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
409 ; tcExtendTyVarEnv tvs $ -- Deriving preds may (now) mention
410 -- the type variables for the type constructor
411 do { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
412 -- The "deriv_pred" is a LHsType to take account of the fact that for
413 -- newtype deriving we allow deriving (forall a. C [a]).
414 ; mkEqnHelp DerivOrigin (tvs++deriv_tvs) cls cls_tys tc_app Nothing } }
417 = panic "derivTyData" -- Caller ensures that only TyData can happen
419 ------------------------------------------------------------------
420 mkEqnHelp :: InstOrigin -> [TyVar] -> Class -> [Type] -> Type
421 -> Maybe ThetaType -- Just => context supplied
422 -- Nothing => context inferred
423 -> TcRn (Maybe EarlyDerivSpec)
424 mkEqnHelp orig tvs cls cls_tys tc_app mtheta
425 | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
426 = do { -- Make tc_app saturated, because that's what the
427 -- mkDataTypeEqn things expect
428 -- It might not be saturated in the standalone deriving case
429 -- derive instance Monad (T a)
430 let extra_tvs = dropList tc_args (tyConTyVars tycon)
431 full_tc_args = tc_args ++ mkTyVarTys extra_tvs
432 full_tvs = tvs ++ extra_tvs
434 ; (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon full_tc_args
436 ; mayDeriveDataTypeable <- doptM Opt_DeriveDataTypeable
437 ; newtype_deriving <- doptM Opt_GeneralizedNewtypeDeriving
439 -- Be careful to test rep_tc here: in the case of families, we want
440 -- to check the instance tycon, not the family tycon
441 ; if isDataTyCon rep_tc then
442 mkDataTypeEqn orig mayDeriveDataTypeable full_tvs cls cls_tys
443 tycon full_tc_args rep_tc rep_tc_args mtheta
445 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving
447 tycon full_tc_args rep_tc rep_tc_args mtheta }
449 = baleOut (derivingThingErr cls cls_tys tc_app
450 (ptext SLIT("Last argument of the instance must be a type application")))
452 baleOut :: Message -> TcM (Maybe a)
453 baleOut err = do { addErrTc err; return Nothing }
456 Auxiliary lookup wrapper which requires that looked up family instances are
457 not type instances. If called with a vanilla tycon, the old type application
461 tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
462 tcLookupFamInstExact tycon tys
463 | not (isOpenTyCon tycon)
464 = return (tycon, tys)
466 = do { maybeFamInst <- tcLookupFamInst tycon tys
467 ; case maybeFamInst of
468 Nothing -> famInstNotFound tycon tys False
469 Just famInst@(_, rep_tys)
470 | not variable_only_subst -> famInstNotFound tycon tys True
471 | otherwise -> return famInst
473 tvs = map (Type.getTyVar
474 "TcDeriv.tcLookupFamInstExact")
476 variable_only_subst = all Type.isTyVarTy rep_tys &&
477 sizeVarSet (mkVarSet tvs) == length tvs
478 -- renaming may have no repetitions
483 %************************************************************************
487 %************************************************************************
490 mkDataTypeEqn :: InstOrigin -> Bool -> [Var] -> Class -> [Type]
491 -> TyCon -> [Type] -> TyCon -> [Type] -> Maybe ThetaType
492 -> TcRn (Maybe EarlyDerivSpec) -- Return 'Nothing' if error
494 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
495 tycon tc_args rep_tc rep_tc_args mtheta
496 | Just err <- checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
497 -- NB: pass the *representation* tycon to checkSideConditions
498 = baleOut (derivingThingErr cls cls_tys (mkTyConApp tycon tc_args) err)
501 = ASSERT( null cls_tys )
502 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
504 mk_data_eqn :: InstOrigin -> [TyVar] -> Class
505 -> TyCon -> [TcType] -> TyCon -> [TcType] -> Maybe ThetaType
506 -> TcM (Maybe EarlyDerivSpec)
507 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
508 | cls `hasKey` typeableClassKey
509 = -- The Typeable class is special in several ways
510 -- data T a b = ... deriving( Typeable )
512 -- instance Typeable2 T where ...
514 -- 1. There are no constraints in the instance
515 -- 2. There are no type variables either
516 -- 3. The actual class we want to generate isn't necessarily
517 -- Typeable; it depends on the arity of the type
518 do { real_clas <- tcLookupClass (typeableClassNames !! tyConArity tycon)
519 ; dfun_name <- new_dfun_name real_clas tycon
521 ; return (Just $ Right $
522 DS { ds_loc = loc, ds_orig = orig, ds_name = dfun_name, ds_tvs = []
523 , ds_cls = real_clas, ds_tys = [mkTyConApp tycon []]
524 , ds_theta = mtheta `orElse` [], ds_newtype = False }) }
527 = do { dfun_name <- new_dfun_name cls tycon
529 ; let ordinary_constraints
530 = [ mkClassPred cls [arg_ty]
531 | data_con <- tyConDataCons rep_tc,
532 arg_ty <- ASSERT( isVanillaDataCon data_con )
533 dataConInstOrigArgTys data_con rep_tc_args,
534 not (isUnLiftedType arg_ty) ] -- No constraints for unlifted types?
536 stupid_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
537 stupid_constraints = substTheta stupid_subst (tyConStupidTheta rep_tc)
538 all_constraints = stupid_constraints ++ ordinary_constraints
539 -- see Note [Data decl contexts] above
541 spec = DS { ds_loc = loc, ds_orig = orig
542 , ds_name = dfun_name, ds_tvs = tvs
543 , ds_cls = cls, ds_tys = [mkTyConApp tycon tc_args]
544 , ds_theta = mtheta `orElse` all_constraints
545 , ds_newtype = False }
547 ; return (if isJust mtheta then Just (Right spec) -- Specified context
548 else Just (Left spec)) } -- Infer context
550 ------------------------------------------------------------------
551 -- Check side conditions that dis-allow derivability for particular classes
552 -- This is *apart* from the newtype-deriving mechanism
554 -- Here we get the representation tycon in case of family instances as it has
555 -- the data constructors - but we need to be careful to fall back to the
556 -- family tycon (with indexes) in error messages.
558 checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> Maybe SDoc
559 checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
561 = Just ty_args_why -- e.g. deriving( Foo s )
563 = case [cond | (key,cond) <- sideConditions, key == getUnique cls] of
564 [] -> Just (non_std_why cls)
565 [cond] -> cond (mayDeriveDataTypeable, rep_tc)
566 _other -> pprPanic "checkSideConditions" (ppr cls)
568 ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("is not a class")
570 non_std_why :: Class -> SDoc
571 non_std_why cls = quotes (ppr cls) <+> ptext SLIT("is not a derivable class")
573 sideConditions :: [(Unique, Condition)]
575 = [ (eqClassKey, cond_std),
576 (ordClassKey, cond_std),
577 (readClassKey, cond_std),
578 (showClassKey, cond_std),
579 (enumClassKey, cond_std `andCond` cond_isEnumeration),
580 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
581 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
582 (typeableClassKey, cond_mayDeriveDataTypeable `andCond` cond_typeableOK),
583 (dataClassKey, cond_mayDeriveDataTypeable `andCond` cond_std)
586 type Condition = (Bool, TyCon) -> Maybe SDoc
587 -- Bool is whether or not we are allowed to derive Data and Typeable
588 -- TyCon is the *representation* tycon if the
589 -- data type is an indexed one
592 orCond :: Condition -> Condition -> Condition
595 Nothing -> Nothing -- c1 succeeds
596 Just x -> case c2 tc of -- c1 fails
598 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
601 andCond :: Condition -> Condition -> Condition
602 andCond c1 c2 tc = case c1 tc of
603 Nothing -> c2 tc -- c1 succeeds
604 Just x -> Just x -- c1 fails
606 cond_std :: Condition
608 | any (not . isVanillaDataCon) data_cons = Just existential_why
609 | null data_cons = Just no_cons_why
610 | otherwise = Nothing
612 data_cons = tyConDataCons rep_tc
613 no_cons_why = quotes (pprSourceTyCon rep_tc) <+>
614 ptext SLIT("has no data constructors")
615 existential_why = quotes (pprSourceTyCon rep_tc) <+>
616 ptext SLIT("has non-Haskell-98 constructor(s)")
618 cond_isEnumeration :: Condition
619 cond_isEnumeration (_, rep_tc)
620 | isEnumerationTyCon rep_tc = Nothing
621 | otherwise = Just why
623 why = quotes (pprSourceTyCon rep_tc) <+>
624 ptext SLIT("has non-nullary constructors")
626 cond_isProduct :: Condition
627 cond_isProduct (_, rep_tc)
628 | isProductTyCon rep_tc = Nothing
629 | otherwise = Just why
631 why = quotes (pprSourceTyCon rep_tc) <+>
632 ptext SLIT("has more than one constructor")
634 cond_typeableOK :: Condition
635 -- OK for Typeable class
636 -- Currently: (a) args all of kind *
637 -- (b) 7 or fewer args
638 cond_typeableOK (_, rep_tc)
639 | tyConArity rep_tc > 7 = Just too_many
640 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc))
642 | isFamInstTyCon rep_tc = Just fam_inst -- no Typable for family insts
643 | otherwise = Nothing
645 too_many = quotes (pprSourceTyCon rep_tc) <+>
646 ptext SLIT("has too many arguments")
647 bad_kind = quotes (pprSourceTyCon rep_tc) <+>
648 ptext SLIT("has arguments of kind other than `*'")
649 fam_inst = quotes (pprSourceTyCon rep_tc) <+>
650 ptext SLIT("is a type family")
652 cond_mayDeriveDataTypeable :: Condition
653 cond_mayDeriveDataTypeable (mayDeriveDataTypeable, _)
654 | mayDeriveDataTypeable = Nothing
655 | otherwise = Just why
657 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
659 std_class_via_iso :: Class -> Bool
660 std_class_via_iso clas -- These standard classes can be derived for a newtype
661 -- using the isomorphism trick *even if no -fglasgow-exts*
662 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
663 -- Not Read/Show because they respect the type
664 -- Not Enum, because newtypes are never in Enum
667 new_dfun_name :: Class -> TyCon -> TcM Name
668 new_dfun_name clas tycon -- Just a simple wrapper
669 = newDFunName clas [mkTyConApp tycon []] (getSrcSpan tycon)
670 -- The type passed to newDFunName is only used to generate
671 -- a suitable string; hence the empty type arg list
675 %************************************************************************
679 %************************************************************************
682 mkNewTypeEqn :: InstOrigin -> Bool -> Bool -> [Var] -> Class
683 -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
685 -> TcRn (Maybe EarlyDerivSpec)
686 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving tvs
687 cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
688 | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
689 = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
690 ; dfun_name <- new_dfun_name cls tycon
692 ; let spec = DS { ds_loc = loc, ds_orig = orig
693 , ds_name = dfun_name, ds_tvs = dict_tvs
694 , ds_cls = cls, ds_tys = inst_tys
695 , ds_theta = mtheta `orElse` all_preds
696 , ds_newtype = True }
697 ; return (if isJust mtheta then Just (Right spec)
698 else Just (Left spec)) }
700 | isNothing mb_std_err -- Use the standard H98 method
701 = mk_data_eqn orig tvs cls tycon tc_args rep_tycon rep_tc_args mtheta
703 -- Otherwise we can't derive
704 | newtype_deriving = baleOut cant_derive_err -- Too hard
705 | otherwise = baleOut std_err -- Just complain about being a non-std instance
707 mb_std_err = checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tycon
708 std_err = derivingThingErr cls cls_tys tc_app $
709 vcat [fromJust mb_std_err,
710 ptext SLIT("Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")]
712 -- Here is the plan for newtype derivings. We see
713 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
714 -- where t is a type,
715 -- ak+1...an is a suffix of a1..an, and are all tyars
716 -- ak+1...an do not occur free in t, nor in the s1..sm
717 -- (C s1 ... sm) is a *partial applications* of class C
718 -- with the last parameter missing
719 -- (T a1 .. ak) matches the kind of C's last argument
720 -- (and hence so does t)
722 -- We generate the instance
723 -- instance forall ({a1..ak} u fvs(s1..sm)).
724 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
725 -- where T a1...ap is the partial application of
726 -- the LHS of the correct kind and p >= k
728 -- NB: the variables below are:
729 -- tc_tvs = [a1, ..., an]
730 -- tyvars_to_keep = [a1, ..., ak]
731 -- rep_ty = t ak .. an
732 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
733 -- tys = [s1, ..., sm]
736 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
737 -- We generate the instance
738 -- instance Monad (ST s) => Monad (T s) where
740 cls_tyvars = classTyVars cls
741 kind = tyVarKind (last cls_tyvars)
742 -- Kind of the thing we want to instance
743 -- e.g. argument kind of Monad, *->*
745 (arg_kinds, _) = splitKindFunTys kind
746 n_args_to_drop = length arg_kinds
747 -- Want to drop 1 arg from (T s a) and (ST s a)
748 -- to get instance Monad (ST s) => Monad (T s)
750 -- Note [newtype representation]
751 -- Need newTyConRhs *not* newTyConRep to get the representation
752 -- type, because the latter looks through all intermediate newtypes
754 -- newtype B = MkB Int
755 -- newtype A = MkA B deriving( Num )
756 -- We want the Num instance of B, *not* the Num instance of Int,
757 -- when making the Num instance of A!
758 rep_ty = newTyConInstRhs rep_tycon rep_tc_args
759 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
761 n_tyargs_to_keep = tyConArity tycon - n_args_to_drop
762 dropped_tc_args = drop n_tyargs_to_keep tc_args
763 dropped_tvs = tyVarsOfTypes dropped_tc_args
765 n_args_to_keep = length rep_ty_args - n_args_to_drop
766 args_to_drop = drop n_args_to_keep rep_ty_args
767 args_to_keep = take n_args_to_keep rep_ty_args
769 rep_fn' = mkAppTys rep_fn args_to_keep
770 rep_tys = cls_tys ++ [rep_fn']
771 rep_pred = mkClassPred cls rep_tys
772 -- rep_pred is the representation dictionary, from where
773 -- we are gong to get all the methods for the newtype
776 tc_app = mkTyConApp tycon (take n_tyargs_to_keep tc_args)
778 -- Next we figure out what superclass dictionaries to use
779 -- See Note [Newtype deriving superclasses] above
781 inst_tys = cls_tys ++ [tc_app]
782 sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
785 -- If there are no tyvars, there's no need
786 -- to abstract over the dictionaries we need
787 -- Example: newtype T = MkT Int deriving( C )
788 -- We get the derived instance
791 -- instance C Int => C T
792 dict_tvs = filterOut (`elemVarSet` dropped_tvs) tvs
793 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
795 -------------------------------------------------------------------
796 -- Figuring out whether we can only do this newtype-deriving thing
798 right_arity = length cls_tys + 1 == classArity cls
800 -- Never derive Read,Show,Typeable,Data this way
801 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
802 can_derive_via_isomorphism
803 = not (getUnique cls `elem` non_iso_classes)
804 && right_arity -- Well kinded;
805 -- eg not: newtype T ... deriving( ST )
806 -- because ST needs *2* type params
807 && n_tyargs_to_keep >= 0 -- Type constructor has right kind:
808 -- eg not: newtype T = T Int deriving( Monad )
809 && n_args_to_keep >= 0 -- Rep type has right kind:
810 -- eg not: newtype T a = T Int deriving( Monad )
811 && eta_ok -- Eta reduction works
812 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
813 -- newtype A = MkA [A]
815 -- instance Eq [A] => Eq A !!
816 -- Here's a recursive newtype that's actually OK
817 -- newtype S1 = S1 [T1 ()]
818 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
819 -- It's currently rejected. Oh well.
820 -- In fact we generate an instance decl that has method of form
821 -- meth @ instTy = meth @ repTy
822 -- (no coerce's). We'd need a coerce if we wanted to handle
823 -- recursive newtypes too
825 -- Check that eta reduction is OK
826 eta_ok = (args_to_drop `tcEqTypes` dropped_tc_args)
827 -- (a) the dropped-off args are identical in the source and rep type
828 -- newtype T a b = MkT (S [a] b) deriving( Monad )
829 -- Here the 'b' must be the same in the rep type (S [a] b)
831 && (tyVarsOfType rep_fn' `disjointVarSet` dropped_tvs)
832 -- (b) the remaining type args do not mention any of the dropped
835 && (tyVarsOfTypes cls_tys `disjointVarSet` dropped_tvs)
836 -- (c) the type class args do not mention any of the dropped type
839 && all isTyVarTy dropped_tc_args
840 -- (d) in case of newtype family instances, the eta-dropped
841 -- arguments must be type variables (not more complex indexes)
843 cant_derive_err = derivingThingErr cls cls_tys tc_app
844 (vcat [ptext SLIT("even with cunning newtype deriving:"),
845 if isRecursiveTyCon tycon then
846 ptext SLIT("the newtype may be recursive")
848 if not right_arity then
849 quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("does not have arity 1")
851 if not (n_tyargs_to_keep >= 0) then
852 ptext SLIT("the type constructor has wrong kind")
853 else if not (n_args_to_keep >= 0) then
854 ptext SLIT("the representation type has wrong kind")
855 else if not eta_ok then
856 ptext SLIT("the eta-reduction property does not hold")
862 %************************************************************************
864 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
866 %************************************************************************
868 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
869 terms, which is the final correct RHS for the corresponding original
873 Each (k,TyVarTy tv) in a solution constrains only a type
877 The (k,TyVarTy tv) pairs in a solution are canonically
878 ordered by sorting on type varible, tv, (major key) and then class, k,
883 inferInstanceContexts :: OverlapFlag -> [DerivSpec] -> TcM [DerivSpec]
885 inferInstanceContexts _ [] = return []
887 inferInstanceContexts oflag infer_specs
888 = do { traceTc (text "inferInstanceContexts" <+> vcat (map pprDerivSpec infer_specs))
889 ; iterate_deriv 1 initial_solutions }
891 ------------------------------------------------------------------
892 -- The initial solutions for the equations claim that each
893 -- instance has an empty context; this solution is certainly
894 -- in canonical form.
895 initial_solutions :: [ThetaType]
896 initial_solutions = [ [] | _ <- infer_specs ]
898 ------------------------------------------------------------------
899 -- iterate_deriv calculates the next batch of solutions,
900 -- compares it with the current one; finishes if they are the
901 -- same, otherwise recurses with the new solutions.
902 -- It fails if any iteration fails
903 iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec]
904 iterate_deriv n current_solns
905 | n > 20 -- Looks as if we are in an infinite loop
906 -- This can happen if we have -fallow-undecidable-instances
907 -- (See TcSimplify.tcSimplifyDeriv.)
908 = pprPanic "solveDerivEqns: probable loop"
909 (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
911 = do { -- Extend the inst info from the explicit instance decls
912 -- with the current set of solutions, and simplify each RHS
913 let inst_specs = zipWithEqual "add_solns" (mkInstance2 oflag)
914 current_solns infer_specs
915 ; new_solns <- checkNoErrs $
916 extendLocalInstEnv inst_specs $
917 mapM gen_soln infer_specs
919 ; if (current_solns == new_solns) then
920 return [ spec { ds_theta = soln }
921 | (spec, soln) <- zip infer_specs current_solns ]
923 iterate_deriv (n+1) new_solns }
925 ------------------------------------------------------------------
926 gen_soln :: DerivSpec -> TcM [PredType]
927 gen_soln (DS { ds_loc = loc, ds_orig = orig, ds_tvs = tyvars
928 , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
930 addErrCtxt (derivInstCtxt clas inst_tys) $
931 do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
932 -- checkValidInstance tyvars theta clas inst_tys
933 -- Not necessary; see Note [Exotic derived instance contexts]
936 -- Check for a bizarre corner case, when the derived instance decl should
937 -- have form instance C a b => D (T a) where ...
938 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
939 -- of problems; in particular, it's hard to compare solutions for
940 -- equality when finding the fixpoint. So I just rule it out for now.
941 ; let tv_set = mkVarSet tyvars
942 weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]
943 ; mapM_ (addErrTc . badDerivedPred) weird_preds
945 -- Claim: the result instance declaration is guaranteed valid
946 -- Hence no need to call:
947 -- checkValidInstance tyvars theta clas inst_tys
948 ; return (sortLe (<=) theta) } -- Canonicalise before returning the solution
950 ------------------------------------------------------------------
951 mkInstance1 :: OverlapFlag -> DerivSpec -> Instance
952 mkInstance1 overlap_flag spec = mkInstance2 overlap_flag (ds_theta spec) spec
954 mkInstance2 :: OverlapFlag -> ThetaType -> DerivSpec -> Instance
955 mkInstance2 overlap_flag theta
956 (DS { ds_name = dfun_name
957 , ds_tvs = tyvars, ds_cls = clas, ds_tys = tys })
958 = mkLocalInstance dfun overlap_flag
960 dfun = mkDictFunId dfun_name tyvars theta clas tys
963 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
964 -- Add new locally-defined instances; don't bother to check
965 -- for functional dependency errors -- that'll happen in TcInstDcls
966 extendLocalInstEnv dfuns thing_inside
967 = do { env <- getGblEnv
968 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
969 env' = env { tcg_inst_env = inst_env' }
970 ; setGblEnv env' thing_inside }
974 %************************************************************************
976 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
978 %************************************************************************
980 After all the trouble to figure out the required context for the
981 derived instance declarations, all that's left is to chug along to
982 produce them. They will then be shoved into @tcInstDecls2@, which
983 will do all its usual business.
985 There are lots of possibilities for code to generate. Here are
986 various general remarks.
991 We want derived instances of @Eq@ and @Ord@ (both v common) to be
992 ``you-couldn't-do-better-by-hand'' efficient.
995 Deriving @Show@---also pretty common--- should also be reasonable good code.
998 Deriving for the other classes isn't that common or that big a deal.
1005 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
1008 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
1011 We {\em normally} generate code only for the non-defaulted methods;
1012 there are some exceptions for @Eq@ and (especially) @Ord@...
1015 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
1016 constructor's numeric (@Int#@) tag. These are generated by
1017 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
1018 these is around is given by @hasCon2TagFun@.
1020 The examples under the different sections below will make this
1024 Much less often (really just for deriving @Ix@), we use a
1025 @_tag2con_<tycon>@ function. See the examples.
1028 We use the renamer!!! Reason: we're supposed to be
1029 producing @LHsBinds Name@ for the methods, but that means
1030 producing correctly-uniquified code on the fly. This is entirely
1031 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
1032 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
1033 the renamer. What a great hack!
1037 -- Generate the InstInfo for the required instance paired with the
1038 -- *representation* tycon for that instance,
1039 -- plus any auxiliary bindings required
1041 -- Representation tycons differ from the tycon in the instance signature in
1042 -- case of instances for indexed families.
1044 genInst :: OverlapFlag -> DerivSpec -> TcM (InstInfo, DerivAuxBinds)
1047 = return (InstInfo { iSpec = mkInstance1 oflag spec
1048 , iBinds = NewTypeDerived }, [])
1051 = do { fix_env <- getFixityEnv
1053 inst = mkInstance1 oflag spec
1054 (tyvars,_,clas,[ty]) = instanceHead inst
1055 clas_nm = className clas
1056 (visible_tycon, tyArgs) = tcSplitTyConApp ty
1058 -- In case of a family instance, we need to use the representation
1059 -- tycon (after all, it has the data constructors)
1060 ; (tycon, _) <- tcLookupFamInstExact visible_tycon tyArgs
1061 ; let (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
1063 -- Bring the right type variables into
1064 -- scope, and rename the method binds
1065 -- It's a bit yukky that we return *renamed* InstInfo, but
1066 -- *non-renamed* auxiliary bindings
1067 ; (rn_meth_binds, _fvs) <- discardWarnings $
1068 bindLocalNames (map Var.varName tyvars) $
1069 rnMethodBinds clas_nm (\_ -> []) [] meth_binds
1071 -- Build the InstInfo
1072 ; return (InstInfo { iSpec = inst,
1073 iBinds = VanillaInst rn_meth_binds [] },
1077 genDerivBinds :: Class -> FixityEnv -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1078 genDerivBinds clas fix_env tycon
1079 | className clas `elem` typeableClassNames
1080 = (gen_Typeable_binds tycon, [])
1083 = case assocMaybe gen_list (getUnique clas) of
1084 Just gen_fn -> gen_fn tycon
1085 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1087 gen_list :: [(Unique, TyCon -> (LHsBinds RdrName, DerivAuxBinds))]
1088 gen_list = [(eqClassKey, gen_Eq_binds)
1089 ,(ordClassKey, gen_Ord_binds)
1090 ,(enumClassKey, gen_Enum_binds)
1091 ,(boundedClassKey, gen_Bounded_binds)
1092 ,(ixClassKey, gen_Ix_binds)
1093 ,(showClassKey, gen_Show_binds fix_env)
1094 ,(readClassKey, gen_Read_binds fix_env)
1095 ,(dataClassKey, gen_Data_binds fix_env)
1100 %************************************************************************
1102 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1104 %************************************************************************
1107 derivingThingErr :: Class -> [Type] -> Type -> Message -> Message
1108 derivingThingErr clas tys ty why
1109 = sep [hsep [ptext SLIT("Can't make a derived instance of"),
1111 nest 2 (parens why)]
1113 pred = mkClassPred clas (tys ++ [ty])
1115 standaloneCtxt :: LHsType Name -> SDoc
1116 standaloneCtxt ty = ptext SLIT("In the stand-alone deriving instance for") <+> quotes (ppr ty)
1118 derivInstCtxt :: Class -> [Type] -> Message
1119 derivInstCtxt clas inst_tys
1120 = ptext SLIT("When deriving the instance for") <+> parens (pprClassPred clas inst_tys)
1122 badDerivedPred :: PredType -> Message
1124 = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
1125 ptext SLIT("type variables that are not data type parameters"),
1126 nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]
1128 famInstNotFound :: TyCon -> [Type] -> Bool -> TcM a
1129 famInstNotFound tycon tys notExact
1130 = failWithTc (msg <+> quotes (pprTypeApp tycon (ppr tycon) tys))
1132 msg = ptext $ if notExact
1133 then SLIT("No family instance exactly matching")
1134 else SLIT("More than one family instance for")