+\begin{code}
+makeDerivSpecs :: [LTyClDecl Name]
+ -> [LInstDecl Name]
+ -> [LDerivDecl Name]
+ -> TcM [EarlyDerivSpec]
+
+makeDerivSpecs tycl_decls inst_decls deriv_decls
+ = do { eqns1 <- mapAndRecoverM deriveTyData $
+ extractTyDataPreds tycl_decls ++
+ [ pd -- traverse assoc data families
+ | L _ (InstDecl _ _ _ ats) <- inst_decls
+ , pd <- extractTyDataPreds ats ]
+ ; eqns2 <- mapAndRecoverM deriveStandalone deriv_decls
+ ; return (catMaybes (eqns1 ++ eqns2)) }
+ where
+ extractTyDataPreds decls =
+ [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
+
+
+------------------------------------------------------------------
+deriveStandalone :: LDerivDecl Name -> TcM (Maybe EarlyDerivSpec)
+-- Standalone deriving declarations
+-- e.g. deriving instance show a => Show (T a)
+-- Rather like tcLocalInstDecl
+deriveStandalone (L loc (DerivDecl deriv_ty))
+ = setSrcSpan loc $
+ addErrCtxt (standaloneCtxt deriv_ty) $
+ do { traceTc (text "standalone deriving decl for" <+> ppr deriv_ty)
+ ; (tvs, theta, tau) <- tcHsInstHead deriv_ty
+ ; traceTc (text "standalone deriving;"
+ <+> text "tvs:" <+> ppr tvs
+ <+> text "theta:" <+> ppr theta
+ <+> text "tau:" <+> ppr tau)
+ ; (cls, inst_tys) <- checkValidInstHead tau
+ ; checkValidInstance tvs theta cls inst_tys
+ -- C.f. TcInstDcls.tcLocalInstDecl1
+
+ ; let cls_tys = take (length inst_tys - 1) inst_tys
+ inst_ty = last inst_tys
+ ; traceTc (text "standalone deriving;"
+ <+> text "class:" <+> ppr cls
+ <+> text "class types:" <+> ppr cls_tys
+ <+> text "type:" <+> ppr inst_ty)
+ ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
+ (Just theta) }
+
+------------------------------------------------------------------
+deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM (Maybe EarlyDerivSpec)
+deriveTyData (L loc deriv_pred, L _ decl@(TyData { tcdLName = L _ tycon_name,
+ tcdTyVars = tv_names,
+ tcdTyPats = ty_pats }))
+ = setSrcSpan loc $ -- Use the location of the 'deriving' item
+ tcAddDeclCtxt decl $
+ do { let hs_ty_args = ty_pats `orElse` map (nlHsTyVar . hsLTyVarName) tv_names
+ hs_app = nlHsTyConApp tycon_name hs_ty_args
+ -- We get kinding info for the tyvars by typechecking (T a b)
+ -- Hence forming a tycon application and then dis-assembling it
+ ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
+ ; tcExtendTyVarEnv tvs $ -- Deriving preds may (now) mention
+ -- the type variables for the type constructor
+ do { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
+ -- The "deriv_pred" is a LHsType to take account of the fact that for
+ -- newtype deriving we allow deriving (forall a. C [a]).
+ ; mkEqnHelp DerivOrigin (tvs++deriv_tvs) cls cls_tys tc_app Nothing } }
+
+deriveTyData _other
+ = panic "derivTyData" -- Caller ensures that only TyData can happen
+
+------------------------------------------------------------------
+mkEqnHelp :: InstOrigin -> [TyVar] -> Class -> [Type] -> Type
+ -> Maybe ThetaType -- Just => context supplied (standalone deriving)
+ -- Nothing => context inferred (deriving on data decl)
+ -> TcRn (Maybe EarlyDerivSpec)
+mkEqnHelp orig tvs cls cls_tys tc_app mtheta
+ | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
+ , isAlgTyCon tycon -- Check for functions, primitive types etc
+ = do { (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon tc_args
+ -- Be careful to test rep_tc here: in the case of families,
+ -- we want to check the instance tycon, not the family tycon
+
+ -- For standalone deriving (mtheta /= Nothing),
+ -- check that all the data constructors are in scope
+ -- By this time we know that the thing is algebraic
+ -- because we've called checkInstHead in derivingStandalone
+ ; rdr_env <- getGlobalRdrEnv
+ ; let hidden_data_cons = isAbstractTyCon rep_tc || any not_in_scope (tyConDataCons rep_tc)
+ not_in_scope dc = null (lookupGRE_Name rdr_env (dataConName dc))
+ ; checkTc (isNothing mtheta || not hidden_data_cons)
+ (derivingHiddenErr tycon)
+
+ ; mayDeriveDataTypeable <- doptM Opt_DeriveDataTypeable
+ ; newtype_deriving <- doptM Opt_GeneralizedNewtypeDeriving
+
+ ; if isDataTyCon rep_tc then
+ mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
+ tycon tc_args rep_tc rep_tc_args mtheta
+ else
+ mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving
+ tvs cls cls_tys
+ tycon tc_args rep_tc rep_tc_args mtheta }
+ | otherwise
+ = baleOut (derivingThingErr cls cls_tys tc_app
+ (ptext (sLit "The last argument of the instance must be a data or newtype application")))
+
+baleOut :: Message -> TcM (Maybe a)
+baleOut err = do { addErrTc err; return Nothing }
+\end{code}
+
+Note [Looking up family instances for deriving]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+tcLookupFamInstExact is an auxiliary lookup wrapper which requires
+that looked-up family instances exist. If called with a vanilla
+tycon, the old type application is simply returned.
+
+If we have
+ data instance F () = ... deriving Eq
+ data instance F () = ... deriving Eq
+then tcLookupFamInstExact will be confused by the two matches;
+but that can't happen because tcInstDecls1 doesn't call tcDeriving
+if there are any overlaps.
+
+There are two other things that might go wrong with the lookup.
+First, we might see a standalone deriving clause
+ deriving Eq (F ())
+when there is no data instance F () in scope.
+
+Note that it's OK to have
+ data instance F [a] = ...
+ deriving Eq (F [(a,b)])
+where the match is not exact; the same holds for ordinary data types
+with standalone deriving declrations.
+
+\begin{code}
+tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
+tcLookupFamInstExact tycon tys
+ | not (isOpenTyCon tycon)
+ = return (tycon, tys)
+ | otherwise
+ = do { maybeFamInst <- tcLookupFamInst tycon tys
+ ; case maybeFamInst of
+ Nothing -> famInstNotFound tycon tys
+ Just famInst -> return famInst
+ }
+
+famInstNotFound :: TyCon -> [Type] -> TcM a
+famInstNotFound tycon tys
+ = failWithTc (ptext (sLit "No family instance for")
+ <+> quotes (pprTypeApp tycon (ppr tycon) tys))
+\end{code}