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
56 %************************************************************************
60 %************************************************************************
64 1. Convert the decls (i.e. data/newtype deriving clauses,
65 plus standalone deriving) to [EarlyDerivSpec]
67 2. Infer the missing contexts for the Left DerivSpecs
69 3. Add the derived bindings, generating InstInfos
72 -- DerivSpec is purely local to this module
73 data DerivSpec = DS { ds_loc :: SrcSpan
74 , ds_orig :: InstOrigin
77 , ds_theta :: ThetaType
81 , ds_tc_args :: [Type]
82 , ds_newtype :: Bool }
83 -- This spec implies a dfun declaration of the form
84 -- df :: forall tvs. theta => C tys
85 -- The Name is the name for the DFun we'll build
86 -- The tyvars bind all the variables in the theta
87 -- For family indexes, the tycon in
88 -- in ds_tys is the *family* tycon
89 -- in ds_tc, ds_tc_args is the *representation* tycon
90 -- For non-family tycons, both are the same
92 -- ds_newtype = True <=> Newtype deriving
93 -- False <=> Vanilla deriving
95 type DerivContext = Maybe ThetaType
96 -- Nothing <=> Vanilla deriving; infer the context of the instance decl
97 -- Just theta <=> Standalone deriving: context supplied by programmer
99 type EarlyDerivSpec = Either DerivSpec DerivSpec
100 -- Left ds => the context for the instance should be inferred
101 -- In this case ds_theta is the list of all the
102 -- constraints needed, such as (Eq [a], Eq a)
103 -- The inference process is to reduce this to a
104 -- simpler form (e.g. Eq a)
106 -- Right ds => the exact context for the instance is supplied
107 -- by the programmer; it is ds_theta
109 pprDerivSpec :: DerivSpec -> SDoc
110 pprDerivSpec (DS { ds_loc = l, ds_name = n, ds_tvs = tvs,
111 ds_cls = c, ds_tys = tys, ds_theta = rhs })
112 = parens (hsep [ppr l, ppr n, ppr tvs, ppr c, ppr tys]
113 <+> equals <+> ppr rhs)
117 Inferring missing contexts
118 ~~~~~~~~~~~~~~~~~~~~~~~~~~
121 data T a b = C1 (Foo a) (Bar b)
126 [NOTE: See end of these comments for what to do with
127 data (C a, D b) => T a b = ...
130 We want to come up with an instance declaration of the form
132 instance (Ping a, Pong b, ...) => Eq (T a b) where
135 It is pretty easy, albeit tedious, to fill in the code "...". The
136 trick is to figure out what the context for the instance decl is,
137 namely @Ping@, @Pong@ and friends.
139 Let's call the context reqd for the T instance of class C at types
140 (a,b, ...) C (T a b). Thus:
142 Eq (T a b) = (Ping a, Pong b, ...)
144 Now we can get a (recursive) equation from the @data@ decl:
146 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
147 u Eq (T b a) u Eq Int -- From C2
148 u Eq (T a a) -- From C3
150 Foo and Bar may have explicit instances for @Eq@, in which case we can
151 just substitute for them. Alternatively, either or both may have
152 their @Eq@ instances given by @deriving@ clauses, in which case they
153 form part of the system of equations.
155 Now all we need do is simplify and solve the equations, iterating to
156 find the least fixpoint. Notice that the order of the arguments can
157 switch around, as here in the recursive calls to T.
159 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
163 Eq (T a b) = {} -- The empty set
166 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
167 u Eq (T b a) u Eq Int -- From C2
168 u Eq (T a a) -- From C3
170 After simplification:
171 = Eq a u Ping b u {} u {} u {}
176 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
177 u Eq (T b a) u Eq Int -- From C2
178 u Eq (T a a) -- From C3
180 After simplification:
185 = Eq a u Ping b u Eq b u Ping a
187 The next iteration gives the same result, so this is the fixpoint. We
188 need to make a canonical form of the RHS to ensure convergence. We do
189 this by simplifying the RHS to a form in which
191 - the classes constrain only tyvars
192 - the list is sorted by tyvar (major key) and then class (minor key)
193 - no duplicates, of course
195 So, here are the synonyms for the ``equation'' structures:
198 Note [Data decl contexts]
199 ~~~~~~~~~~~~~~~~~~~~~~~~~
202 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
204 We will need an instance decl like:
206 instance (Read a, RealFloat a) => Read (Complex a) where
209 The RealFloat in the context is because the read method for Complex is bound
210 to construct a Complex, and doing that requires that the argument type is
213 But this ain't true for Show, Eq, Ord, etc, since they don't construct
214 a Complex; they only take them apart.
216 Our approach: identify the offending classes, and add the data type
217 context to the instance decl. The "offending classes" are
221 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
222 pattern matching against a constructor from a data type with a context
223 gives rise to the constraints for that context -- or at least the thinned
224 version. So now all classes are "offending".
226 Note [Newtype deriving]
227 ~~~~~~~~~~~~~~~~~~~~~~~
231 newtype T = T Char deriving( C [a] )
233 Notice the free 'a' in the deriving. We have to fill this out to
234 newtype T = T Char deriving( forall a. C [a] )
236 And then translate it to:
237 instance C [a] Char => C [a] T where ...
240 Note [Newtype deriving superclasses]
241 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
242 (See also Trac #1220 for an interesting exchange on newtype
243 deriving and superclasses.)
245 The 'tys' here come from the partial application in the deriving
246 clause. The last arg is the new instance type.
248 We must pass the superclasses; the newtype might be an instance
249 of them in a different way than the representation type
250 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
251 Then the Show instance is not done via isomorphism; it shows
253 The Num instance is derived via isomorphism, but the Show superclass
254 dictionary must the Show instance for Foo, *not* the Show dictionary
255 gotten from the Num dictionary. So we must build a whole new dictionary
256 not just use the Num one. The instance we want is something like:
257 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
260 There may be a coercion needed which we get from the tycon for the newtype
261 when the dict is constructed in TcInstDcls.tcInstDecl2
264 Note [Unused constructors and deriving clauses]
265 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
266 See Trac #3221. Consider
267 data T = T1 | T2 deriving( Show )
268 Are T1 and T2 unused? Well, no: the deriving clause expands to mention
269 both of them. So we gather defs/uses from deriving just like anything else.
271 %************************************************************************
273 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
275 %************************************************************************
278 tcDeriving :: [LTyClDecl Name] -- All type constructors
279 -> [LInstDecl Name] -- All instance declarations
280 -> [LDerivDecl Name] -- All stand-alone deriving declarations
281 -> TcM ([InstInfo Name], -- The generated "instance decls"
282 HsValBinds Name, -- Extra generated top-level bindings
285 tcDeriving tycl_decls inst_decls deriv_decls
286 = recoverM (return ([], emptyValBindsOut, emptyDUs)) $
287 do { -- Fish the "deriving"-related information out of the TcEnv
288 -- And make the necessary "equations".
289 is_boot <- tcIsHsBoot
290 ; traceTc (text "tcDeriving" <+> ppr is_boot)
291 ; early_specs <- makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
293 ; overlap_flag <- getOverlapFlag
294 ; let (infer_specs, given_specs) = splitEithers early_specs
295 ; insts1 <- mapM (genInst True overlap_flag) given_specs
297 ; final_specs <- extendLocalInstEnv (map (iSpec . fst) insts1) $
298 inferInstanceContexts overlap_flag infer_specs
300 ; insts2 <- mapM (genInst False overlap_flag) final_specs
302 -- Generate the generic to/from functions from each type declaration
303 ; gen_binds <- mkGenericBinds is_boot tycl_decls
304 ; (inst_info, rn_binds, rn_dus) <- renameDeriv is_boot gen_binds (insts1 ++ insts2)
307 ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
308 (ddump_deriving inst_info rn_binds))
310 ; return (inst_info, rn_binds, rn_dus) }
312 ddump_deriving :: [InstInfo Name] -> HsValBinds Name -> SDoc
313 ddump_deriving inst_infos extra_binds
314 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
316 renameDeriv :: Bool -> LHsBinds RdrName
317 -> [(InstInfo RdrName, DerivAuxBinds)]
318 -> TcM ([InstInfo Name], HsValBinds Name, DefUses)
319 renameDeriv is_boot gen_binds insts
320 | is_boot -- If we are compiling a hs-boot file, don't generate any derived bindings
321 -- The inst-info bindings will all be empty, but it's easier to
322 -- just use rn_inst_info to change the type appropriately
323 = do { (rn_inst_infos, fvs) <- mapAndUnzipM rn_inst_info inst_infos
324 ; return (rn_inst_infos, emptyValBindsOut, usesOnly (plusFVs fvs)) }
327 = discardWarnings $ -- Discard warnings about unused bindings etc
328 do { (rn_gen, dus_gen) <- setOptM Opt_ScopedTypeVariables $ -- Type signatures in patterns
329 -- are used in the generic binds
330 rnTopBinds (ValBindsIn gen_binds [])
331 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to be kept alive
333 -- Generate and rename any extra not-one-inst-decl-specific binds,
334 -- notably "con2tag" and/or "tag2con" functions.
335 -- Bring those names into scope before renaming the instances themselves
336 ; loc <- getSrcSpanM -- Generic loc for shared bindings
337 ; let aux_binds = listToBag $ map (genAuxBind loc) $
338 rm_dups [] $ concat deriv_aux_binds
339 ; rn_aux_lhs <- rnTopBindsLHS emptyFsEnv (ValBindsIn aux_binds [])
340 ; let aux_names = map unLoc (collectHsValBinders rn_aux_lhs)
342 ; bindLocalNames aux_names $
343 do { (rn_aux, dus_aux) <- rnTopBindsRHS (mkNameSet aux_names) rn_aux_lhs
344 ; (rn_inst_infos, fvs_insts) <- mapAndUnzipM rn_inst_info inst_infos
345 ; return (rn_inst_infos, rn_aux `plusHsValBinds` rn_gen,
346 dus_gen `plusDU` dus_aux `plusDU` usesOnly (plusFVs fvs_insts)) } }
349 (inst_infos, deriv_aux_binds) = unzip insts
351 -- Remove duplicate requests for auxilliary bindings
353 rm_dups acc (b:bs) | any (isDupAux b) acc = rm_dups acc bs
354 | otherwise = rm_dups (b:acc) bs
357 rn_inst_info (InstInfo { iSpec = inst, iBinds = NewTypeDerived co })
358 = return (InstInfo { iSpec = inst, iBinds = NewTypeDerived co }, emptyFVs)
360 rn_inst_info (InstInfo { iSpec = inst, iBinds = VanillaInst binds sigs standalone_deriv })
361 = -- Bring the right type variables into
362 -- scope (yuk), and rename the method binds
364 bindLocalNames (map Var.varName tyvars) $
365 do { (rn_binds, fvs) <- rnMethodBinds clas_nm (\_ -> []) [] binds
366 ; let binds' = VanillaInst rn_binds [] standalone_deriv
367 ; return (InstInfo { iSpec = inst, iBinds = binds' }, fvs) }
369 (tyvars,_, clas,_) = instanceHead inst
370 clas_nm = className clas
372 -----------------------------------------
373 mkGenericBinds :: Bool -> [LTyClDecl Name] -> TcM (LHsBinds RdrName)
374 mkGenericBinds is_boot tycl_decls
378 = do { tcs <- mapM tcLookupTyCon [ tcdName d
379 | L _ d <- tycl_decls, isDataDecl d ]
380 ; return (unionManyBags [ mkTyConGenericBinds tc
381 | tc <- tcs, tyConHasGenerics tc ]) }
382 -- We are only interested in the data type declarations,
383 -- and then only in the ones whose 'has-generics' flag is on
384 -- The predicate tyConHasGenerics finds both of these
388 %************************************************************************
390 From HsSyn to DerivSpec
392 %************************************************************************
394 @makeDerivSpecs@ fishes around to find the info about needed derived instances.
397 makeDerivSpecs :: Bool
401 -> TcM [EarlyDerivSpec]
403 makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
404 | is_boot -- No 'deriving' at all in hs-boot files
405 = do { mapM_ add_deriv_err deriv_locs
408 = do { eqns1 <- mapAndRecoverM deriveTyData all_tydata
409 ; eqns2 <- mapAndRecoverM deriveStandalone deriv_decls
410 ; return (eqns1 ++ eqns2) }
412 extractTyDataPreds decls
413 = [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
415 all_tydata :: [(LHsType Name, LTyClDecl Name)]
416 -- Derived predicate paired with its data type declaration
417 all_tydata = extractTyDataPreds tycl_decls ++
418 [ pd -- Traverse assoc data families
419 | L _ (InstDecl _ _ _ ats) <- inst_decls
420 , pd <- extractTyDataPreds ats ]
422 deriv_locs = map (getLoc . snd) all_tydata
423 ++ map getLoc deriv_decls
425 add_deriv_err loc = setSrcSpan loc $
426 addErr (hang (ptext (sLit "Deriving not permitted in hs-boot file"))
427 2 (ptext (sLit "Use an instance declaration instead")))
429 ------------------------------------------------------------------
430 deriveStandalone :: LDerivDecl Name -> TcM EarlyDerivSpec
431 -- Standalone deriving declarations
432 -- e.g. deriving instance Show a => Show (T a)
433 -- Rather like tcLocalInstDecl
434 deriveStandalone (L loc (DerivDecl deriv_ty))
436 addErrCtxt (standaloneCtxt deriv_ty) $
437 do { traceTc (text "standalone deriving decl for" <+> ppr deriv_ty)
438 ; (tvs, theta, tau) <- tcHsInstHead deriv_ty
439 ; traceTc (text "standalone deriving;"
440 <+> text "tvs:" <+> ppr tvs
441 <+> text "theta:" <+> ppr theta
442 <+> text "tau:" <+> ppr tau)
443 ; (cls, inst_tys) <- checkValidInstHead tau
444 ; checkValidInstance tvs theta cls inst_tys
445 -- C.f. TcInstDcls.tcLocalInstDecl1
447 ; let cls_tys = take (length inst_tys - 1) inst_tys
448 inst_ty = last inst_tys
449 ; traceTc (text "standalone deriving;"
450 <+> text "class:" <+> ppr cls
451 <+> text "class types:" <+> ppr cls_tys
452 <+> text "type:" <+> ppr inst_ty)
453 ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
456 ------------------------------------------------------------------
457 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM EarlyDerivSpec
458 deriveTyData (L loc deriv_pred, L _ decl@(TyData { tcdLName = L _ tycon_name,
459 tcdTyVars = tv_names,
460 tcdTyPats = ty_pats }))
461 = setSrcSpan loc $ -- Use the location of the 'deriving' item
463 do { (tvs, tc, tc_args) <- get_lhs ty_pats
464 ; tcExtendTyVarEnv tvs $ -- Deriving preds may (now) mention
465 -- the type variables for the type constructor
467 do { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
468 -- The "deriv_pred" is a LHsType to take account of the fact that for
469 -- newtype deriving we allow deriving (forall a. C [a]).
471 -- Given data T a b c = ... deriving( C d ),
472 -- we want to drop type variables from T so that (C d (T a)) is well-kinded
473 ; let cls_tyvars = classTyVars cls
474 kind = tyVarKind (last cls_tyvars)
475 (arg_kinds, _) = splitKindFunTys kind
476 n_args_to_drop = length arg_kinds
477 n_args_to_keep = tyConArity tc - n_args_to_drop
478 args_to_drop = drop n_args_to_keep tc_args
479 inst_ty = mkTyConApp tc (take n_args_to_keep tc_args)
480 inst_ty_kind = typeKind inst_ty
481 dropped_tvs = mkVarSet (mapCatMaybes getTyVar_maybe args_to_drop)
482 univ_tvs = (mkVarSet tvs `extendVarSetList` deriv_tvs)
483 `minusVarSet` dropped_tvs
485 -- Check that the result really is well-kinded
486 ; checkTc (n_args_to_keep >= 0 && (inst_ty_kind `eqKind` kind))
487 (derivingKindErr tc cls cls_tys kind)
489 ; checkTc (sizeVarSet dropped_tvs == n_args_to_drop && -- (a)
490 tyVarsOfTypes (inst_ty:cls_tys) `subVarSet` univ_tvs) -- (b)
491 (derivingEtaErr cls cls_tys inst_ty)
493 -- (a) The data type can be eta-reduced; eg reject:
494 -- data instance T a a = ... deriving( Monad )
495 -- (b) The type class args do not mention any of the dropped type
497 -- newtype T a s = ... deriving( ST s )
499 -- Type families can't be partially applied
500 -- e.g. newtype instance T Int a = MkT [a] deriving( Monad )
501 -- Note [Deriving, type families, and partial applications]
502 ; checkTc (not (isOpenTyCon tc) || n_args_to_drop == 0)
503 (typeFamilyPapErr tc cls cls_tys inst_ty)
505 ; mkEqnHelp DerivOrigin (varSetElems univ_tvs) cls cls_tys inst_ty Nothing } }
507 -- Tiresomely we must figure out the "lhs", which is awkward for type families
508 -- E.g. data T a b = .. deriving( Eq )
509 -- Here, the lhs is (T a b)
510 -- data instance TF Int b = ... deriving( Eq )
511 -- Here, the lhs is (TF Int b)
512 -- But if we just look up the tycon_name, we get is the *family*
513 -- tycon, but not pattern types -- they are in the *rep* tycon.
514 get_lhs Nothing = do { tc <- tcLookupTyCon tycon_name
515 ; let tvs = tyConTyVars tc
516 ; return (tvs, tc, mkTyVarTys tvs) }
517 get_lhs (Just pats) = do { let hs_app = nlHsTyConApp tycon_name pats
518 ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
519 ; let (tc, tc_args) = tcSplitTyConApp tc_app
520 ; return (tvs, tc, tc_args) }
523 = panic "derivTyData" -- Caller ensures that only TyData can happen
526 Note [Deriving, type families, and partial applications]
527 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
528 When there are no type families, it's quite easy:
530 newtype S a = MkS [a]
531 -- :CoS :: S ~ [] -- Eta-reduced
533 instance Eq [a] => Eq (S a) -- by coercion sym (Eq (coMkS a)) : Eq [a] ~ Eq (S a)
534 instance Monad [] => Monad S -- by coercion sym (Monad coMkS) : Monad [] ~ Monad S
536 When type familes are involved it's trickier:
539 newtype instance T Int a = MkT [a] deriving( Eq, Monad )
540 -- :RT is the representation type for (T Int a)
541 -- :CoF:R1T a :: T Int a ~ :RT a -- Not eta reduced
542 -- :Co:R1T :: :RT ~ [] -- Eta-reduced
544 instance Eq [a] => Eq (T Int a) -- easy by coercion
545 instance Monad [] => Monad (T Int) -- only if we can eta reduce???
547 The "???" bit is that we don't build the :CoF thing in eta-reduced form
548 Henc the current typeFamilyPapErr, even though the instance makes sense.
549 After all, we can write it out
550 instance Monad [] => Monad (T Int) -- only if we can eta reduce???
555 mkEqnHelp :: InstOrigin -> [TyVar] -> Class -> [Type] -> Type
556 -> DerivContext -- Just => context supplied (standalone deriving)
557 -- Nothing => context inferred (deriving on data decl)
558 -> TcRn EarlyDerivSpec
559 -- Make the EarlyDerivSpec for an instance
560 -- forall tvs. theta => cls (tys ++ [ty])
561 -- where the 'theta' is optional (that's the Maybe part)
562 -- Assumes that this declaration is well-kinded
564 mkEqnHelp orig tvs cls cls_tys tc_app mtheta
565 | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
566 , isAlgTyCon tycon -- Check for functions, primitive types etc
567 = do { (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon tc_args
568 -- Be careful to test rep_tc here: in the case of families,
569 -- we want to check the instance tycon, not the family tycon
571 -- For standalone deriving (mtheta /= Nothing),
572 -- check that all the data constructors are in scope.
573 -- No need for this when deriving Typeable, becuase we don't need
574 -- the constructors for that.
575 ; rdr_env <- getGlobalRdrEnv
576 ; let hidden_data_cons = isAbstractTyCon rep_tc || any not_in_scope (tyConDataCons rep_tc)
577 not_in_scope dc = null (lookupGRE_Name rdr_env (dataConName dc))
578 ; checkTc (isNothing mtheta ||
579 not hidden_data_cons ||
580 className cls `elem` typeableClassNames)
581 (derivingHiddenErr tycon)
584 ; if isDataTyCon rep_tc then
585 mkDataTypeEqn orig dflags tvs cls cls_tys
586 tycon tc_args rep_tc rep_tc_args mtheta
588 mkNewTypeEqn orig dflags tvs cls cls_tys
589 tycon tc_args rep_tc rep_tc_args mtheta }
591 = failWithTc (derivingThingErr False cls cls_tys tc_app
592 (ptext (sLit "The last argument of the instance must be a data or newtype application")))
595 Note [Looking up family instances for deriving]
596 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
597 tcLookupFamInstExact is an auxiliary lookup wrapper which requires
598 that looked-up family instances exist. If called with a vanilla
599 tycon, the old type application is simply returned.
602 data instance F () = ... deriving Eq
603 data instance F () = ... deriving Eq
604 then tcLookupFamInstExact will be confused by the two matches;
605 but that can't happen because tcInstDecls1 doesn't call tcDeriving
606 if there are any overlaps.
608 There are two other things that might go wrong with the lookup.
609 First, we might see a standalone deriving clause
611 when there is no data instance F () in scope.
613 Note that it's OK to have
614 data instance F [a] = ...
615 deriving Eq (F [(a,b)])
616 where the match is not exact; the same holds for ordinary data types
617 with standalone deriving declrations.
620 tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
621 tcLookupFamInstExact tycon tys
622 | not (isOpenTyCon tycon)
623 = return (tycon, tys)
625 = do { maybeFamInst <- tcLookupFamInst tycon tys
626 ; case maybeFamInst of
627 Nothing -> famInstNotFound tycon tys
628 Just famInst -> return famInst
631 famInstNotFound :: TyCon -> [Type] -> TcM a
632 famInstNotFound tycon tys
633 = failWithTc (ptext (sLit "No family instance for")
634 <+> quotes (pprTypeApp tycon tys))
638 %************************************************************************
642 %************************************************************************
645 mkDataTypeEqn :: InstOrigin
647 -> [Var] -- Universally quantified type variables in the instance
648 -> Class -- Class for which we need to derive an instance
649 -> [Type] -- Other parameters to the class except the last
650 -> TyCon -- Type constructor for which the instance is requested
651 -- (last parameter to the type class)
652 -> [Type] -- Parameters to the type constructor
653 -> TyCon -- rep of the above (for type families)
654 -> [Type] -- rep of the above
655 -> DerivContext -- Context of the instance, for standalone deriving
656 -> TcRn EarlyDerivSpec -- Return 'Nothing' if error
658 mkDataTypeEqn orig dflags tvs cls cls_tys
659 tycon tc_args rep_tc rep_tc_args mtheta
660 = case checkSideConditions dflags mtheta cls cls_tys rep_tc of
661 -- NB: pass the *representation* tycon to checkSideConditions
662 CanDerive -> go_for_it
663 NonDerivableClass -> bale_out (nonStdErr cls)
664 DerivableClassError msg -> bale_out msg
666 go_for_it = mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
667 bale_out msg = failWithTc (derivingThingErr False cls cls_tys (mkTyConApp tycon tc_args) msg)
669 mk_data_eqn, mk_typeable_eqn
670 :: InstOrigin -> [TyVar] -> Class
671 -> TyCon -> [TcType] -> TyCon -> [TcType] -> DerivContext
672 -> TcM EarlyDerivSpec
673 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
674 | getName cls `elem` typeableClassNames
675 = mk_typeable_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
678 = do { dfun_name <- new_dfun_name cls tycon
680 ; let inst_tys = [mkTyConApp tycon tc_args]
681 inferred_constraints = inferConstraints tvs cls inst_tys rep_tc rep_tc_args
682 spec = DS { ds_loc = loc, ds_orig = orig
683 , ds_name = dfun_name, ds_tvs = tvs
684 , ds_cls = cls, ds_tys = inst_tys
685 , ds_tc = rep_tc, ds_tc_args = rep_tc_args
686 , ds_theta = mtheta `orElse` inferred_constraints
687 , ds_newtype = False }
689 ; return (if isJust mtheta then Right spec -- Specified context
690 else Left spec) } -- Infer context
692 mk_typeable_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
693 -- The Typeable class is special in several ways
694 -- data T a b = ... deriving( Typeable )
696 -- instance Typeable2 T where ...
698 -- 1. There are no constraints in the instance
699 -- 2. There are no type variables either
700 -- 3. The actual class we want to generate isn't necessarily
701 -- Typeable; it depends on the arity of the type
702 | isNothing mtheta -- deriving on a data type decl
703 = do { checkTc (cls `hasKey` typeableClassKey)
704 (ptext (sLit "Use deriving( Typeable ) on a data type declaration"))
705 ; real_cls <- tcLookupClass (typeableClassNames !! tyConArity tycon)
706 ; mk_typeable_eqn orig tvs real_cls tycon [] rep_tc [] (Just []) }
708 | otherwise -- standaone deriving
709 = do { checkTc (null tc_args)
710 (ptext (sLit "Derived typeable instance must be of form (Typeable")
711 <> int (tyConArity tycon) <+> ppr tycon <> rparen)
712 ; dfun_name <- new_dfun_name cls tycon
715 DS { ds_loc = loc, ds_orig = orig, ds_name = dfun_name, ds_tvs = []
716 , ds_cls = cls, ds_tys = [mkTyConApp tycon []]
717 , ds_tc = rep_tc, ds_tc_args = rep_tc_args
718 , ds_theta = mtheta `orElse` [], ds_newtype = False }) }
721 inferConstraints :: [TyVar] -> Class -> [TcType] -> TyCon -> [TcType] -> ThetaType
722 -- Generate a sufficiently large set of constraints that typechecking the
723 -- generated method definitions should succeed. This set will be simplified
724 -- before being used in the instance declaration
725 inferConstraints tvs cls inst_tys rep_tc rep_tc_args
726 = ASSERT2( equalLength rep_tc_tvs all_rep_tc_args, ppr cls <+> ppr rep_tc )
727 stupid_constraints ++ extra_constraints
728 ++ sc_constraints ++ con_arg_constraints
730 -- Constraints arising from the arguments of each constructor
732 = [ mkClassPred cls [arg_ty]
733 | data_con <- tyConDataCons rep_tc,
734 arg_ty <- ASSERT( isVanillaDataCon data_con )
735 get_constrained_tys $
736 dataConInstOrigArgTys data_con all_rep_tc_args,
737 not (isUnLiftedType arg_ty) ]
738 -- No constraints for unlifted types
739 -- Where they are legal we generate specilised function calls
741 -- For functor-like classes, two things are different
742 -- (a) We recurse over argument types to generate constraints
743 -- See Functor examples in TcGenDeriv
744 -- (b) The rep_tc_args will be one short
745 is_functor_like = getUnique cls `elem` functorLikeClassKeys
747 get_constrained_tys :: [Type] -> [Type]
748 get_constrained_tys tys
749 | is_functor_like = concatMap (deepSubtypesContaining last_tv) tys
752 rep_tc_tvs = tyConTyVars rep_tc
753 last_tv = last rep_tc_tvs
754 all_rep_tc_args | is_functor_like = rep_tc_args ++ [mkTyVarTy last_tv]
755 | otherwise = rep_tc_args
757 -- Constraints arising from superclasses
758 -- See Note [Superclasses of derived instance]
759 sc_constraints = substTheta (zipOpenTvSubst (classTyVars cls) inst_tys)
762 -- Stupid constraints
763 stupid_constraints = substTheta subst (tyConStupidTheta rep_tc)
764 subst = zipTopTvSubst rep_tc_tvs all_rep_tc_args
767 -- The Data class (only) requires that for
768 -- instance (...) => Data (T a b)
769 -- then (Data a, Data b) are among the (...) constraints
770 -- Reason: that's what you need to typecheck the method
771 -- dataCast1 f = gcast1 f
773 | cls `hasKey` dataClassKey = [mkClassPred cls [mkTyVarTy tv] | tv <- tvs]
776 ------------------------------------------------------------------
777 -- Check side conditions that dis-allow derivability for particular classes
778 -- This is *apart* from the newtype-deriving mechanism
780 -- Here we get the representation tycon in case of family instances as it has
781 -- the data constructors - but we need to be careful to fall back to the
782 -- family tycon (with indexes) in error messages.
784 data DerivStatus = CanDerive
785 | DerivableClassError SDoc -- Standard class, but can't do it
786 | NonDerivableClass -- Non-standard class
788 checkSideConditions :: DynFlags -> DerivContext -> Class -> [TcType] -> TyCon -> DerivStatus
789 checkSideConditions dflags mtheta cls cls_tys rep_tc
790 | Just cond <- sideConditions mtheta cls
791 = case (cond (dflags, rep_tc)) of
792 Just err -> DerivableClassError err -- Class-specific error
793 Nothing | null cls_tys -> CanDerive -- All derivable classes are unary, so
794 -- cls_tys (the type args other than last)
796 | otherwise -> DerivableClassError ty_args_why -- e.g. deriving( Eq s )
797 | otherwise = NonDerivableClass -- Not a standard class
799 ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "is not a class")
801 nonStdErr :: Class -> SDoc
802 nonStdErr cls = quotes (ppr cls) <+> ptext (sLit "is not a derivable class")
804 sideConditions :: DerivContext -> Class -> Maybe Condition
805 sideConditions mtheta cls
806 | cls_key == eqClassKey = Just cond_std
807 | cls_key == ordClassKey = Just cond_std
808 | cls_key == showClassKey = Just cond_std
809 | cls_key == readClassKey = Just (cond_std `andCond` cond_noUnliftedArgs)
810 | cls_key == enumClassKey = Just (cond_std `andCond` cond_isEnumeration)
811 | cls_key == ixClassKey = Just (cond_std `andCond` cond_enumOrProduct)
812 | cls_key == boundedClassKey = Just (cond_std `andCond` cond_enumOrProduct)
813 | cls_key == dataClassKey = Just (checkFlag Opt_DeriveDataTypeable `andCond`
814 cond_std `andCond` cond_noUnliftedArgs)
815 | cls_key == functorClassKey = Just (checkFlag Opt_DeriveFunctor `andCond`
816 cond_functorOK True) -- NB: no cond_std!
817 | cls_key == foldableClassKey = Just (checkFlag Opt_DeriveFoldable `andCond`
818 cond_functorOK False) -- Functor/Fold/Trav works ok for rank-n types
819 | cls_key == traversableClassKey = Just (checkFlag Opt_DeriveTraversable `andCond`
820 cond_functorOK False)
821 | getName cls `elem` typeableClassNames = Just (checkFlag Opt_DeriveDataTypeable `andCond` cond_typeableOK)
822 | otherwise = Nothing
824 cls_key = getUnique cls
825 cond_std = cond_stdOK mtheta
827 type Condition = (DynFlags, TyCon) -> Maybe SDoc
828 -- first Bool is whether or not we are allowed to derive Data and Typeable
829 -- second Bool is whether or not we are allowed to derive Functor
830 -- TyCon is the *representation* tycon if the
831 -- data type is an indexed one
834 orCond :: Condition -> Condition -> Condition
837 Nothing -> Nothing -- c1 succeeds
838 Just x -> case c2 tc of -- c1 fails
840 Just y -> Just (x $$ ptext (sLit " and") $$ y)
843 andCond :: Condition -> Condition -> Condition
844 andCond c1 c2 tc = case c1 tc of
845 Nothing -> c2 tc -- c1 succeeds
846 Just x -> Just x -- c1 fails
848 cond_stdOK :: DerivContext -> Condition
849 cond_stdOK (Just _) _
850 = Nothing -- Don't check these conservative conditions for
851 -- standalone deriving; just generate the code
852 cond_stdOK Nothing (_, rep_tc)
853 | null data_cons = Just (no_cons_why $$ suggestion)
854 | not (null con_whys) = Just (vcat con_whys $$ suggestion)
855 | otherwise = Nothing
857 suggestion = ptext (sLit "Possible fix: use a standalone deriving declaration instead")
858 data_cons = tyConDataCons rep_tc
859 no_cons_why = quotes (pprSourceTyCon rep_tc) <+>
860 ptext (sLit "has no data constructors")
862 con_whys = mapCatMaybes check_con data_cons
864 check_con :: DataCon -> Maybe SDoc
866 | isVanillaDataCon con
867 , all isTauTy (dataConOrigArgTys con) = Nothing
868 | otherwise = Just (badCon con (ptext (sLit "does not have a Haskell-98 type")))
870 cond_enumOrProduct :: Condition
871 cond_enumOrProduct = cond_isEnumeration `orCond`
872 (cond_isProduct `andCond` cond_noUnliftedArgs)
874 cond_noUnliftedArgs :: Condition
875 -- For some classes (eg Eq, Ord) we allow unlifted arg types
876 -- by generating specilaised code. For others (eg Data) we don't.
877 cond_noUnliftedArgs (_, tc)
878 | null bad_cons = Nothing
879 | otherwise = Just why
881 bad_cons = [ con | con <- tyConDataCons tc
882 , any isUnLiftedType (dataConOrigArgTys con) ]
883 why = badCon (head bad_cons) (ptext (sLit "has arguments of unlifted type"))
885 cond_isEnumeration :: Condition
886 cond_isEnumeration (_, rep_tc)
887 | isEnumerationTyCon rep_tc = Nothing
888 | otherwise = Just why
890 why = quotes (pprSourceTyCon rep_tc) <+>
891 ptext (sLit "has non-nullary constructors")
893 cond_isProduct :: Condition
894 cond_isProduct (_, rep_tc)
895 | isProductTyCon rep_tc = Nothing
896 | otherwise = Just why
898 why = quotes (pprSourceTyCon rep_tc) <+>
899 ptext (sLit "has more than one constructor")
901 cond_typeableOK :: Condition
902 -- OK for Typeable class
903 -- Currently: (a) args all of kind *
904 -- (b) 7 or fewer args
905 cond_typeableOK (_, rep_tc)
906 | tyConArity rep_tc > 7 = Just too_many
907 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc))
909 | isFamInstTyCon rep_tc = Just fam_inst -- no Typable for family insts
910 | otherwise = Nothing
912 too_many = quotes (pprSourceTyCon rep_tc) <+>
913 ptext (sLit "has too many arguments")
914 bad_kind = quotes (pprSourceTyCon rep_tc) <+>
915 ptext (sLit "has arguments of kind other than `*'")
916 fam_inst = quotes (pprSourceTyCon rep_tc) <+>
917 ptext (sLit "is a type family")
920 functorLikeClassKeys :: [Unique]
921 functorLikeClassKeys = [functorClassKey, foldableClassKey, traversableClassKey]
923 cond_functorOK :: Bool -> Condition
924 -- OK for Functor class
925 -- Currently: (a) at least one argument
926 -- (b) don't use argument contravariantly
927 -- (c) don't use argument in the wrong place, e.g. data T a = T (X a a)
928 -- (d) optionally: don't use function types
929 cond_functorOK allowFunctions (dflags, rep_tc)
930 | not (dopt Opt_DeriveFunctor dflags)
931 = Just (ptext (sLit "You need -XDeriveFunctor to derive an instance for this class"))
933 = msum (map check_con data_cons) -- msum picks the first 'Just', if any
935 data_cons = tyConDataCons rep_tc
936 check_con con = msum (check_vanilla con : foldDataConArgs (ft_check con) con)
938 check_vanilla :: DataCon -> Maybe SDoc
939 check_vanilla con | isVanillaDataCon con = Nothing
940 | otherwise = Just (badCon con existential)
942 ft_check :: DataCon -> FFoldType (Maybe SDoc)
943 ft_check con = FT { ft_triv = Nothing, ft_var = Nothing
944 , ft_co_var = Just (badCon con covariant)
945 , ft_fun = \x y -> if allowFunctions then x `mplus` y
946 else Just (badCon con functions)
947 , ft_tup = \_ xs -> msum xs
948 , ft_ty_app = \_ x -> x
949 , ft_bad_app = Just (badCon con wrong_arg)
950 , ft_forall = \_ x -> x }
952 existential = ptext (sLit "has existential arguments")
953 covariant = ptext (sLit "uses the type variable in a function argument")
954 functions = ptext (sLit "contains function types")
955 wrong_arg = ptext (sLit "uses the type variable in an argument other than the last")
957 checkFlag :: DynFlag -> Condition
958 checkFlag flag (dflags, _)
959 | dopt flag dflags = Nothing
960 | otherwise = Just why
962 why = ptext (sLit "You need -X") <> text flag_str
963 <+> ptext (sLit "to derive an instance for this class")
964 flag_str = case [ s | (s, f, _) <- xFlags, f==flag ] of
966 other -> pprPanic "checkFlag" (ppr other)
968 std_class_via_iso :: Class -> Bool
969 std_class_via_iso clas -- These standard classes can be derived for a newtype
970 -- using the isomorphism trick *even if no -fglasgow-exts*
971 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
972 -- Not Read/Show because they respect the type
973 -- Not Enum, because newtypes are never in Enum
976 new_dfun_name :: Class -> TyCon -> TcM Name
977 new_dfun_name clas tycon -- Just a simple wrapper
978 = do { loc <- getSrcSpanM -- The location of the instance decl, not of the tycon
979 ; newDFunName clas [mkTyConApp tycon []] loc }
980 -- The type passed to newDFunName is only used to generate
981 -- a suitable string; hence the empty type arg list
983 badCon :: DataCon -> SDoc -> SDoc
984 badCon con msg = ptext (sLit "Constructor") <+> quotes (ppr con) <+> msg
987 Note [Superclasses of derived instance]
988 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
989 In general, a derived instance decl needs the superclasses of the derived
990 class too. So if we have
991 data T a = ...deriving( Ord )
992 then the initial context for Ord (T a) should include Eq (T a). Often this is
993 redundant; we'll also generate an Ord constraint for each constructor argument,
994 and that will probably generate enough constraints to make the Eq (T a) constraint
995 be satisfied too. But not always; consider:
1001 data T a = MkT (S a) deriving( Ord )
1002 instance Num a => Eq (T a)
1004 The derived instance for (Ord (T a)) must have a (Num a) constraint!
1006 data T a = MkT deriving( Data, Typeable )
1007 Here there *is* no argument field, but we must nevertheless generate
1008 a context for the Data instances:
1009 instance Typable a => Data (T a) where ...
1012 %************************************************************************
1016 %************************************************************************
1019 mkNewTypeEqn :: InstOrigin -> DynFlags -> [Var] -> Class
1020 -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
1022 -> TcRn EarlyDerivSpec
1023 mkNewTypeEqn orig dflags tvs
1024 cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
1025 -- Want: instance (...) => cls (cls_tys ++ [tycon tc_args]) where ...
1026 | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
1027 = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
1028 ; dfun_name <- new_dfun_name cls tycon
1029 ; loc <- getSrcSpanM
1030 ; let spec = DS { ds_loc = loc, ds_orig = orig
1031 , ds_name = dfun_name, ds_tvs = varSetElems dfun_tvs
1032 , ds_cls = cls, ds_tys = inst_tys
1033 , ds_tc = rep_tycon, ds_tc_args = rep_tc_args
1034 , ds_theta = mtheta `orElse` all_preds
1035 , ds_newtype = True }
1036 ; return (if isJust mtheta then Right spec
1040 = case checkSideConditions dflags mtheta cls cls_tys rep_tycon of
1041 CanDerive -> go_for_it -- Use the standard H98 method
1042 DerivableClassError msg -> bale_out msg -- Error with standard class
1043 NonDerivableClass -- Must use newtype deriving
1044 | newtype_deriving -> bale_out cant_derive_err -- Too hard, even with newtype deriving
1045 | otherwise -> bale_out non_std_err -- Try newtype deriving!
1047 newtype_deriving = dopt Opt_GeneralizedNewtypeDeriving dflags
1048 go_for_it = mk_data_eqn orig tvs cls tycon tc_args rep_tycon rep_tc_args mtheta
1049 bale_out msg = failWithTc (derivingThingErr newtype_deriving cls cls_tys inst_ty msg)
1051 non_std_err = nonStdErr cls $$
1052 ptext (sLit "Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")
1054 -- Here is the plan for newtype derivings. We see
1055 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
1056 -- where t is a type,
1057 -- ak+1...an is a suffix of a1..an, and are all tyars
1058 -- ak+1...an do not occur free in t, nor in the s1..sm
1059 -- (C s1 ... sm) is a *partial applications* of class C
1060 -- with the last parameter missing
1061 -- (T a1 .. ak) matches the kind of C's last argument
1062 -- (and hence so does t)
1063 -- The latter kind-check has been done by deriveTyData already,
1064 -- and tc_args are already trimmed
1066 -- We generate the instance
1067 -- instance forall ({a1..ak} u fvs(s1..sm)).
1068 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
1069 -- where T a1...ap is the partial application of
1070 -- the LHS of the correct kind and p >= k
1072 -- NB: the variables below are:
1073 -- tc_tvs = [a1, ..., an]
1074 -- tyvars_to_keep = [a1, ..., ak]
1075 -- rep_ty = t ak .. an
1076 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
1077 -- tys = [s1, ..., sm]
1080 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
1081 -- We generate the instance
1082 -- instance Monad (ST s) => Monad (T s) where
1084 nt_eta_arity = length (fst (newTyConEtadRhs rep_tycon))
1085 -- For newtype T a b = MkT (S a a b), the TyCon machinery already
1086 -- eta-reduces the representation type, so we know that
1088 -- That's convenient here, because we may have to apply
1089 -- it to fewer than its original complement of arguments
1091 -- Note [Newtype representation]
1092 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1093 -- Need newTyConRhs (*not* a recursive representation finder)
1094 -- to get the representation type. For example
1095 -- newtype B = MkB Int
1096 -- newtype A = MkA B deriving( Num )
1097 -- We want the Num instance of B, *not* the Num instance of Int,
1098 -- when making the Num instance of A!
1099 rep_inst_ty = newTyConInstRhs rep_tycon rep_tc_args
1100 rep_tys = cls_tys ++ [rep_inst_ty]
1101 rep_pred = mkClassPred cls rep_tys
1102 -- rep_pred is the representation dictionary, from where
1103 -- we are gong to get all the methods for the newtype
1107 -- Next we figure out what superclass dictionaries to use
1108 -- See Note [Newtype deriving superclasses] above
1110 cls_tyvars = classTyVars cls
1111 dfun_tvs = tyVarsOfTypes inst_tys
1112 inst_ty = mkTyConApp tycon tc_args
1113 inst_tys = cls_tys ++ [inst_ty]
1114 sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
1117 -- If there are no tyvars, there's no need
1118 -- to abstract over the dictionaries we need
1119 -- Example: newtype T = MkT Int deriving( C )
1120 -- We get the derived instance
1123 -- instance C Int => C T
1124 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
1126 -------------------------------------------------------------------
1127 -- Figuring out whether we can only do this newtype-deriving thing
1129 can_derive_via_isomorphism
1130 = not (non_iso_class cls)
1134 -- && not (isRecursiveTyCon tycon) -- Note [Recursive newtypes]
1136 -- Never derive Read,Show,Typeable,Data by isomorphism
1137 non_iso_class cls = className cls `elem` ([readClassName, showClassName, dataClassName] ++
1140 arity_ok = length cls_tys + 1 == classArity cls
1141 -- Well kinded; eg not: newtype T ... deriving( ST )
1142 -- because ST needs *2* type params
1144 -- Check that eta reduction is OK
1145 eta_ok = nt_eta_arity <= length rep_tc_args
1146 -- The newtype can be eta-reduced to match the number
1147 -- of type argument actually supplied
1148 -- newtype T a b = MkT (S [a] b) deriving( Monad )
1149 -- Here the 'b' must be the same in the rep type (S [a] b)
1150 -- And the [a] must not mention 'b'. That's all handled
1153 ats_ok = null (classATs cls)
1154 -- No associated types for the class, because we don't
1155 -- currently generate type 'instance' decls; and cannot do
1156 -- so for 'data' instance decls
1159 = vcat [ ppUnless arity_ok arity_msg
1160 , ppUnless eta_ok eta_msg
1161 , ppUnless ats_ok ats_msg ]
1162 arity_msg = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "does not have arity 1")
1163 eta_msg = ptext (sLit "cannot eta-reduce the representation type enough")
1164 ats_msg = ptext (sLit "the class has associated types")
1167 Note [Recursive newtypes]
1168 ~~~~~~~~~~~~~~~~~~~~~~~~~
1169 Newtype deriving works fine, even if the newtype is recursive.
1170 e.g. newtype S1 = S1 [T1 ()]
1171 newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
1172 Remember, too, that type families are curretly (conservatively) given
1173 a recursive flag, so this also allows newtype deriving to work
1176 We used to exclude recursive types, because we had a rather simple
1177 minded way of generating the instance decl:
1179 instance Eq [A] => Eq A -- Makes typechecker loop!
1180 But now we require a simple context, so it's ok.
1183 %************************************************************************
1185 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
1187 %************************************************************************
1189 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
1190 terms, which is the final correct RHS for the corresponding original
1194 Each (k,TyVarTy tv) in a solution constrains only a type
1198 The (k,TyVarTy tv) pairs in a solution are canonically
1199 ordered by sorting on type varible, tv, (major key) and then class, k,
1204 inferInstanceContexts :: OverlapFlag -> [DerivSpec] -> TcM [DerivSpec]
1206 inferInstanceContexts _ [] = return []
1208 inferInstanceContexts oflag infer_specs
1209 = do { traceTc (text "inferInstanceContexts" <+> vcat (map pprDerivSpec infer_specs))
1210 ; iterate_deriv 1 initial_solutions }
1212 ------------------------------------------------------------------
1213 -- The initial solutions for the equations claim that each
1214 -- instance has an empty context; this solution is certainly
1215 -- in canonical form.
1216 initial_solutions :: [ThetaType]
1217 initial_solutions = [ [] | _ <- infer_specs ]
1219 ------------------------------------------------------------------
1220 -- iterate_deriv calculates the next batch of solutions,
1221 -- compares it with the current one; finishes if they are the
1222 -- same, otherwise recurses with the new solutions.
1223 -- It fails if any iteration fails
1224 iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec]
1225 iterate_deriv n current_solns
1226 | n > 20 -- Looks as if we are in an infinite loop
1227 -- This can happen if we have -XUndecidableInstances
1228 -- (See TcSimplify.tcSimplifyDeriv.)
1229 = pprPanic "solveDerivEqns: probable loop"
1230 (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
1232 = do { -- Extend the inst info from the explicit instance decls
1233 -- with the current set of solutions, and simplify each RHS
1234 let inst_specs = zipWithEqual "add_solns" (mkInstance oflag)
1235 current_solns infer_specs
1236 ; new_solns <- checkNoErrs $
1237 extendLocalInstEnv inst_specs $
1238 mapM gen_soln infer_specs
1240 ; if (current_solns == new_solns) then
1241 return [ spec { ds_theta = soln }
1242 | (spec, soln) <- zip infer_specs current_solns ]
1244 iterate_deriv (n+1) new_solns }
1246 ------------------------------------------------------------------
1247 gen_soln :: DerivSpec -> TcM [PredType]
1248 gen_soln (DS { ds_loc = loc, ds_orig = orig, ds_tvs = tyvars
1249 , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
1251 addErrCtxt (derivInstCtxt clas inst_tys) $
1252 do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
1253 -- checkValidInstance tyvars theta clas inst_tys
1254 -- Not necessary; see Note [Exotic derived instance contexts]
1257 -- Check for a bizarre corner case, when the derived instance decl should
1258 -- have form instance C a b => D (T a) where ...
1259 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
1260 -- of problems; in particular, it's hard to compare solutions for
1261 -- equality when finding the fixpoint. So I just rule it out for now.
1262 ; let tv_set = mkVarSet tyvars
1263 weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]
1264 ; mapM_ (addErrTc . badDerivedPred) weird_preds
1266 -- Claim: the result instance declaration is guaranteed valid
1267 -- Hence no need to call:
1268 -- checkValidInstance tyvars theta clas inst_tys
1269 ; return (sortLe (<=) theta) } -- Canonicalise before returning the solution
1271 ------------------------------------------------------------------
1272 mkInstance :: OverlapFlag -> ThetaType -> DerivSpec -> Instance
1273 mkInstance overlap_flag theta
1274 (DS { ds_name = dfun_name
1275 , ds_tvs = tyvars, ds_cls = clas, ds_tys = tys })
1276 = mkLocalInstance dfun overlap_flag
1278 dfun = mkDictFunId dfun_name tyvars theta clas tys
1281 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
1282 -- Add new locally-defined instances; don't bother to check
1283 -- for functional dependency errors -- that'll happen in TcInstDcls
1284 extendLocalInstEnv dfuns thing_inside
1285 = do { env <- getGblEnv
1286 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
1287 env' = env { tcg_inst_env = inst_env' }
1288 ; setGblEnv env' thing_inside }
1292 %************************************************************************
1294 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
1296 %************************************************************************
1298 After all the trouble to figure out the required context for the
1299 derived instance declarations, all that's left is to chug along to
1300 produce them. They will then be shoved into @tcInstDecls2@, which
1301 will do all its usual business.
1303 There are lots of possibilities for code to generate. Here are
1304 various general remarks.
1309 We want derived instances of @Eq@ and @Ord@ (both v common) to be
1310 ``you-couldn't-do-better-by-hand'' efficient.
1313 Deriving @Show@---also pretty common--- should also be reasonable good code.
1316 Deriving for the other classes isn't that common or that big a deal.
1323 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
1326 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
1329 We {\em normally} generate code only for the non-defaulted methods;
1330 there are some exceptions for @Eq@ and (especially) @Ord@...
1333 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
1334 constructor's numeric (@Int#@) tag. These are generated by
1335 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
1336 these is around is given by @hasCon2TagFun@.
1338 The examples under the different sections below will make this
1342 Much less often (really just for deriving @Ix@), we use a
1343 @_tag2con_<tycon>@ function. See the examples.
1346 We use the renamer!!! Reason: we're supposed to be
1347 producing @LHsBinds Name@ for the methods, but that means
1348 producing correctly-uniquified code on the fly. This is entirely
1349 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
1350 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
1351 the renamer. What a great hack!
1355 -- Generate the InstInfo for the required instance paired with the
1356 -- *representation* tycon for that instance,
1357 -- plus any auxiliary bindings required
1359 -- Representation tycons differ from the tycon in the instance signature in
1360 -- case of instances for indexed families.
1362 genInst :: Bool -- True <=> standalone deriving
1364 -> DerivSpec -> TcM (InstInfo RdrName, DerivAuxBinds)
1365 genInst standalone_deriv oflag spec
1367 = return (InstInfo { iSpec = mkInstance oflag (ds_theta spec) spec
1368 , iBinds = NewTypeDerived co }, [])
1371 = do { let loc = getSrcSpan (ds_name spec)
1372 inst = mkInstance oflag (ds_theta spec) spec
1375 -- In case of a family instance, we need to use the representation
1376 -- tycon (after all, it has the data constructors)
1377 ; fix_env <- getFixityEnv
1378 ; let (meth_binds, aux_binds) = genDerivBinds loc fix_env clas rep_tycon
1379 binds = VanillaInst meth_binds [] standalone_deriv
1380 ; return (InstInfo { iSpec = inst, iBinds = binds }, aux_binds)
1383 rep_tycon = ds_tc spec
1384 rep_tc_args = ds_tc_args spec
1385 co1 = case tyConFamilyCoercion_maybe rep_tycon of
1387 Just co_con -> ACo (mkTyConApp co_con rep_tc_args)
1388 co2 = case newTyConCo_maybe rep_tycon of
1389 Nothing -> IdCo -- The newtype is transparent; no need for a cast
1390 Just co_con -> ACo (mkTyConApp co_con rep_tc_args)
1391 co = co1 `mkTransCoI` co2
1393 -- Example: newtype instance N [a] = N1 (Tree a)
1394 -- deriving instance Eq b => Eq (N [(b,b)])
1395 -- From the instance, we get an implicit newtype R1:N a = N1 (Tree a)
1396 -- When dealing with the deriving clause
1397 -- co1 : N [(b,b)] ~ R1:N (b,b)
1398 -- co2 : R1:N (b,b) ~ Tree (b,b)
1399 -- co : N [(b,b)] ~ Tree (b,b)
1401 genDerivBinds :: SrcSpan -> FixityEnv -> Class -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1402 genDerivBinds loc fix_env clas tycon
1403 | className clas `elem` typeableClassNames
1404 = (gen_Typeable_binds loc tycon, [])
1407 = case assocMaybe gen_list (getUnique clas) of
1408 Just gen_fn -> gen_fn loc tycon
1409 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1411 gen_list :: [(Unique, SrcSpan -> TyCon -> (LHsBinds RdrName, DerivAuxBinds))]
1412 gen_list = [(eqClassKey, gen_Eq_binds)
1413 ,(ordClassKey, gen_Ord_binds)
1414 ,(enumClassKey, gen_Enum_binds)
1415 ,(boundedClassKey, gen_Bounded_binds)
1416 ,(ixClassKey, gen_Ix_binds)
1417 ,(showClassKey, gen_Show_binds fix_env)
1418 ,(readClassKey, gen_Read_binds fix_env)
1419 ,(dataClassKey, gen_Data_binds)
1420 ,(functorClassKey, gen_Functor_binds)
1421 ,(foldableClassKey, gen_Foldable_binds)
1422 ,(traversableClassKey, gen_Traversable_binds)
1427 %************************************************************************
1429 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1431 %************************************************************************
1434 derivingKindErr :: TyCon -> Class -> [Type] -> Kind -> Message
1435 derivingKindErr tc cls cls_tys cls_kind
1436 = hang (ptext (sLit "Cannot derive well-kinded instance of form")
1437 <+> quotes (pprClassPred cls cls_tys <+> parens (ppr tc <+> ptext (sLit "..."))))
1438 2 (ptext (sLit "Class") <+> quotes (ppr cls)
1439 <+> ptext (sLit "expects an argument of kind") <+> quotes (pprKind cls_kind))
1441 derivingEtaErr :: Class -> [Type] -> Type -> Message
1442 derivingEtaErr cls cls_tys inst_ty
1443 = sep [ptext (sLit "Cannot eta-reduce to an instance of form"),
1444 nest 2 (ptext (sLit "instance (...) =>")
1445 <+> pprClassPred cls (cls_tys ++ [inst_ty]))]
1447 typeFamilyPapErr :: TyCon -> Class -> [Type] -> Type -> Message
1448 typeFamilyPapErr tc cls cls_tys inst_ty
1449 = hang (ptext (sLit "Derived instance") <+> quotes (pprClassPred cls (cls_tys ++ [inst_ty])))
1450 2 (ptext (sLit "requires illegal partial application of data type family") <+> ppr tc)
1452 derivingThingErr :: Bool -> Class -> [Type] -> Type -> Message -> Message
1453 derivingThingErr newtype_deriving clas tys ty why
1454 = sep [(hang (ptext (sLit "Can't make a derived instance of"))
1455 2 (quotes (ppr pred))
1456 $$ nest 2 extra) <> colon,
1459 extra | newtype_deriving = ptext (sLit "(even with cunning newtype deriving)")
1461 pred = mkClassPred clas (tys ++ [ty])
1463 derivingHiddenErr :: TyCon -> SDoc
1464 derivingHiddenErr tc
1465 = hang (ptext (sLit "The data constructors of") <+> quotes (ppr tc) <+> ptext (sLit "are not all in scope"))
1466 2 (ptext (sLit "so you cannot derive an instance for it"))
1468 standaloneCtxt :: LHsType Name -> SDoc
1469 standaloneCtxt ty = hang (ptext (sLit "In the stand-alone deriving instance for"))
1472 derivInstCtxt :: Class -> [Type] -> Message
1473 derivInstCtxt clas inst_tys
1474 = ptext (sLit "When deriving the instance for") <+> parens (pprClassPred clas inst_tys)
1476 badDerivedPred :: PredType -> Message
1478 = vcat [ptext (sLit "Can't derive instances where the instance context mentions"),
1479 ptext (sLit "type variables that are not data type parameters"),
1480 nest 2 (ptext (sLit "Offending constraint:") <+> ppr pred)]