+ = []
+
+------------------------------------------------------------------
+-- Check side conditions that dis-allow derivability for particular classes
+-- This is *apart* from the newtype-deriving mechanism
+--
+-- Here we get the representation tycon in case of family instances as it has
+-- the data constructors - but we need to be careful to fall back to the
+-- family tycon (with indexes) in error messages.
+
+data DerivStatus = CanDerive
+ | DerivableClassError SDoc -- Standard class, but can't do it
+ | NonDerivableClass -- Non-standard class
+
+checkSideConditions :: DynFlags -> DerivContext -> Class -> [TcType] -> TyCon -> DerivStatus
+checkSideConditions dflags mtheta cls cls_tys rep_tc
+ | Just cond <- sideConditions mtheta cls
+ = case (cond (dflags, rep_tc)) of
+ Just err -> DerivableClassError err -- Class-specific error
+ Nothing | null cls_tys -> CanDerive -- All derivable classes are unary, so
+ -- cls_tys (the type args other than last)
+ -- should be null
+ | otherwise -> DerivableClassError ty_args_why -- e.g. deriving( Eq s )
+ | otherwise = NonDerivableClass -- Not a standard class
+ where
+ ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "is not a class")
+
+checkTypeableConditions :: Condition
+checkTypeableConditions = checkFlag Opt_DeriveDataTypeable `andCond` cond_typeableOK
+
+nonStdErr :: Class -> SDoc
+nonStdErr cls = quotes (ppr cls) <+> ptext (sLit "is not a derivable class")
+
+sideConditions :: DerivContext -> Class -> Maybe Condition
+sideConditions mtheta cls
+ | cls_key == eqClassKey = Just cond_std
+ | cls_key == ordClassKey = Just cond_std
+ | cls_key == showClassKey = Just cond_std
+ | cls_key == readClassKey = Just (cond_std `andCond` cond_noUnliftedArgs)
+ | cls_key == enumClassKey = Just (cond_std `andCond` cond_isEnumeration)
+ | cls_key == ixClassKey = Just (cond_std `andCond` cond_enumOrProduct)
+ | cls_key == boundedClassKey = Just (cond_std `andCond` cond_enumOrProduct)
+ | cls_key == dataClassKey = Just (checkFlag Opt_DeriveDataTypeable `andCond`
+ cond_std `andCond` cond_noUnliftedArgs)
+ | cls_key == functorClassKey = Just (checkFlag Opt_DeriveFunctor `andCond`
+ cond_functorOK True) -- NB: no cond_std!
+ | cls_key == foldableClassKey = Just (checkFlag Opt_DeriveFoldable `andCond`
+ cond_functorOK False) -- Functor/Fold/Trav works ok for rank-n types
+ | cls_key == traversableClassKey = Just (checkFlag Opt_DeriveTraversable `andCond`
+ cond_functorOK False)
+ | cls_key == genClassKey = Just (cond_RepresentableOk `andCond`
+ checkFlag Opt_DeriveGeneric)
+ | otherwise = Nothing
+ where
+ cls_key = getUnique cls
+ cond_std = cond_stdOK mtheta
+
+type Condition = (DynFlags, TyCon) -> Maybe SDoc
+ -- first Bool is whether or not we are allowed to derive Data and Typeable
+ -- second Bool is whether or not we are allowed to derive Functor
+ -- TyCon is the *representation* tycon if the
+ -- data type is an indexed one
+ -- Nothing => OK
+
+orCond :: Condition -> Condition -> Condition
+orCond c1 c2 tc
+ = case c1 tc of
+ Nothing -> Nothing -- c1 succeeds
+ Just x -> case c2 tc of -- c1 fails
+ Nothing -> Nothing
+ Just y -> Just (x $$ ptext (sLit " or") $$ y)
+ -- Both fail
+
+andCond :: Condition -> Condition -> Condition
+andCond c1 c2 tc = case c1 tc of
+ Nothing -> c2 tc -- c1 succeeds
+ Just x -> Just x -- c1 fails
+
+cond_stdOK :: DerivContext -> Condition
+cond_stdOK (Just _) _
+ = Nothing -- Don't check these conservative conditions for
+ -- standalone deriving; just generate the code
+ -- and let the typechecker handle the result
+cond_stdOK Nothing (_, rep_tc)
+ | null data_cons = Just (no_cons_why rep_tc $$ suggestion)
+ | not (null con_whys) = Just (vcat con_whys $$ suggestion)
+ | otherwise = Nothing
+ where
+ suggestion = ptext (sLit "Possible fix: use a standalone deriving declaration instead")
+ data_cons = tyConDataCons rep_tc
+ con_whys = mapCatMaybes check_con data_cons
+
+ check_con :: DataCon -> Maybe SDoc
+ check_con con
+ | isVanillaDataCon con
+ , all isTauTy (dataConOrigArgTys con) = Nothing
+ | otherwise = Just (badCon con (ptext (sLit "must have a Haskell-98 type")))
+
+no_cons_why :: TyCon -> SDoc
+no_cons_why rep_tc = quotes (pprSourceTyCon rep_tc) <+>
+ ptext (sLit "must have at least one data constructor")
+
+cond_RepresentableOk :: Condition
+cond_RepresentableOk (_,t) = canDoGenerics t
+
+cond_enumOrProduct :: Condition
+cond_enumOrProduct = cond_isEnumeration `orCond`
+ (cond_isProduct `andCond` cond_noUnliftedArgs)
+
+cond_noUnliftedArgs :: Condition
+-- For some classes (eg Eq, Ord) we allow unlifted arg types
+-- by generating specilaised code. For others (eg Data) we don't.
+cond_noUnliftedArgs (_, tc)
+ | null bad_cons = Nothing
+ | otherwise = Just why
+ where
+ bad_cons = [ con | con <- tyConDataCons tc
+ , any isUnLiftedType (dataConOrigArgTys con) ]
+ why = badCon (head bad_cons) (ptext (sLit "must have only arguments of lifted type"))
+
+cond_isEnumeration :: Condition
+cond_isEnumeration (_, rep_tc)
+ | isEnumerationTyCon rep_tc = Nothing
+ | otherwise = Just why
+ where
+ why = sep [ quotes (pprSourceTyCon rep_tc) <+>
+ ptext (sLit "must be an enumeration type")
+ , ptext (sLit "(an enumeration consists of one or more nullary, non-GADT constructors)") ]
+ -- See Note [Enumeration types] in TyCon
+
+cond_isProduct :: Condition
+cond_isProduct (_, rep_tc)
+ | isProductTyCon rep_tc = Nothing
+ | otherwise = Just why
+ where
+ why = quotes (pprSourceTyCon rep_tc) <+>
+ ptext (sLit "must have precisely one constructor")
+
+cond_typeableOK :: Condition
+-- OK for Typeable class
+-- Currently: (a) args all of kind *
+-- (b) 7 or fewer args
+cond_typeableOK (_, tc)
+ | tyConArity tc > 7 = Just too_many
+ | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars tc))
+ = Just bad_kind
+ | otherwise = Nothing
+ where
+ too_many = quotes (pprSourceTyCon tc) <+>
+ ptext (sLit "must have 7 or fewer arguments")
+ bad_kind = quotes (pprSourceTyCon tc) <+>
+ ptext (sLit "must only have arguments of kind `*'")
+
+functorLikeClassKeys :: [Unique]
+functorLikeClassKeys = [functorClassKey, foldableClassKey, traversableClassKey]
+
+cond_functorOK :: Bool -> Condition
+-- OK for Functor/Foldable/Traversable class
+-- Currently: (a) at least one argument
+-- (b) don't use argument contravariantly
+-- (c) don't use argument in the wrong place, e.g. data T a = T (X a a)
+-- (d) optionally: don't use function types
+-- (e) no "stupid context" on data type
+cond_functorOK allowFunctions (_, rep_tc)
+ | null tc_tvs
+ = Just (ptext (sLit "Data type") <+> quotes (ppr rep_tc)
+ <+> ptext (sLit "must have some type parameters"))
+
+ | not (null bad_stupid_theta)
+ = Just (ptext (sLit "Data type") <+> quotes (ppr rep_tc)
+ <+> ptext (sLit "must not have a class context") <+> pprTheta bad_stupid_theta)
+
+ | otherwise
+ = msum (map check_con data_cons) -- msum picks the first 'Just', if any
+ where
+ tc_tvs = tyConTyVars rep_tc
+ Just (_, last_tv) = snocView tc_tvs
+ bad_stupid_theta = filter is_bad (tyConStupidTheta rep_tc)
+ is_bad pred = last_tv `elemVarSet` tyVarsOfPred pred
+
+ data_cons = tyConDataCons rep_tc
+ check_con con = msum (check_vanilla con : foldDataConArgs (ft_check con) con)
+
+ check_vanilla :: DataCon -> Maybe SDoc
+ check_vanilla con | isVanillaDataCon con = Nothing
+ | otherwise = Just (badCon con existential)
+
+ ft_check :: DataCon -> FFoldType (Maybe SDoc)
+ ft_check con = FT { ft_triv = Nothing, ft_var = Nothing
+ , ft_co_var = Just (badCon con covariant)
+ , ft_fun = \x y -> if allowFunctions then x `mplus` y
+ else Just (badCon con functions)
+ , ft_tup = \_ xs -> msum xs
+ , ft_ty_app = \_ x -> x
+ , ft_bad_app = Just (badCon con wrong_arg)
+ , ft_forall = \_ x -> x }
+
+ existential = ptext (sLit "must not have existential arguments")
+ covariant = ptext (sLit "must not use the type variable in a function argument")
+ functions = ptext (sLit "must not contain function types")
+ wrong_arg = ptext (sLit "must not use the type variable in an argument other than the last")
+
+checkFlag :: ExtensionFlag -> Condition
+checkFlag flag (dflags, _)
+ | xopt flag dflags = Nothing
+ | otherwise = Just why
+ where
+ why = ptext (sLit "You need -X") <> text flag_str
+ <+> ptext (sLit "to derive an instance for this class")
+ flag_str = case [ s | (s, f, _) <- xFlags, f==flag ] of
+ [s] -> s
+ other -> pprPanic "checkFlag" (ppr other)
+
+std_class_via_iso :: Class -> Bool
+-- These standard classes can be derived for a newtype
+-- using the isomorphism trick *even if no -XGeneralizedNewtypeDeriving
+-- because giving so gives the same results as generating the boilerplate
+std_class_via_iso clas
+ = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
+ -- Not Read/Show because they respect the type
+ -- Not Enum, because newtypes are never in Enum
+
+
+non_iso_class :: Class -> Bool
+-- *Never* derive Read, Show, Typeable, Data, Generic by isomorphism,
+-- even with -XGeneralizedNewtypeDeriving
+non_iso_class cls
+ = classKey cls `elem` ([ readClassKey, showClassKey, dataClassKey
+ , genClassKey] ++ typeableClassKeys)
+
+typeableClassKeys :: [Unique]
+typeableClassKeys = map getUnique typeableClassNames
+
+new_dfun_name :: Class -> TyCon -> TcM Name
+new_dfun_name clas tycon -- Just a simple wrapper
+ = do { loc <- getSrcSpanM -- The location of the instance decl, not of the tycon
+ ; newDFunName clas [mkTyConApp tycon []] loc }
+ -- The type passed to newDFunName is only used to generate
+ -- a suitable string; hence the empty type arg list
+
+badCon :: DataCon -> SDoc -> SDoc
+badCon con msg = ptext (sLit "Constructor") <+> quotes (ppr con) <+> msg
+\end{code}
+
+Note [Superclasses of derived instance]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+In general, a derived instance decl needs the superclasses of the derived
+class too. So if we have
+ data T a = ...deriving( Ord )
+then the initial context for Ord (T a) should include Eq (T a). Often this is
+redundant; we'll also generate an Ord constraint for each constructor argument,
+and that will probably generate enough constraints to make the Eq (T a) constraint
+be satisfied too. But not always; consider:
+
+ data S a = S
+ instance Eq (S a)
+ instance Ord (S a)
+
+ data T a = MkT (S a) deriving( Ord )
+ instance Num a => Eq (T a)
+
+The derived instance for (Ord (T a)) must have a (Num a) constraint!
+Similarly consider:
+ data T a = MkT deriving( Data, Typeable )
+Here there *is* no argument field, but we must nevertheless generate
+a context for the Data instances:
+ instance Typable a => Data (T a) where ...
+
+
+%************************************************************************
+%* *
+ Deriving newtypes
+%* *
+%************************************************************************
+
+\begin{code}
+mkNewTypeEqn :: CtOrigin -> DynFlags -> [Var] -> Class
+ -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
+ -> DerivContext
+ -> TcRn EarlyDerivSpec
+mkNewTypeEqn orig dflags tvs
+ cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
+-- Want: instance (...) => cls (cls_tys ++ [tycon tc_args]) where ...
+ | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
+ = do { traceTc "newtype deriving:" (ppr tycon <+> ppr rep_tys <+> ppr all_preds)
+ ; dfun_name <- new_dfun_name cls tycon
+ ; loc <- getSrcSpanM
+ ; let spec = DS { ds_loc = loc, ds_orig = orig
+ , ds_name = dfun_name, ds_tvs = varSetElems dfun_tvs
+ , ds_cls = cls, ds_tys = inst_tys
+ , ds_tc = rep_tycon, ds_tc_args = rep_tc_args
+ , ds_theta = mtheta `orElse` all_preds
+ , ds_newtype = True }
+ ; return (if isJust mtheta then Right spec
+ else Left spec) }
+
+ | otherwise
+ = case checkSideConditions dflags mtheta cls cls_tys rep_tycon of
+ CanDerive -> go_for_it -- Use the standard H98 method
+ DerivableClassError msg -- Error with standard class
+ | can_derive_via_isomorphism -> bale_out (msg $$ suggest_nd)
+ | otherwise -> bale_out msg
+ NonDerivableClass -- Must use newtype deriving
+ | newtype_deriving -> bale_out cant_derive_err -- Too hard, even with newtype deriving
+ | can_derive_via_isomorphism -> bale_out (non_std $$ suggest_nd) -- Try newtype deriving!
+ | otherwise -> bale_out non_std
+ where
+ newtype_deriving = xopt Opt_GeneralizedNewtypeDeriving dflags
+ go_for_it = mk_data_eqn orig tvs cls tycon tc_args rep_tycon rep_tc_args mtheta
+ bale_out msg = failWithTc (derivingThingErr newtype_deriving cls cls_tys inst_ty msg)
+
+ non_std = nonStdErr cls
+ suggest_nd = ptext (sLit "Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")
+