TcDeriv.lhs 28.1 KB
Newer Older
1
%
2
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 4 5 6 7 8
%
\section[TcDeriv]{Deriving}

Handles @deriving@ clauses on @data@ declarations.

\begin{code}
9
module TcDeriv ( tcDeriving ) where
10

11
#include "HsVersions.h"
12

13
import HsSyn		( HsBinds(..), MonoBinds(..), TyClDecl(..),
14
			  collectMonoBinders )
15
import RdrHsSyn		( RdrNameMonoBinds )
16
import RnHsSyn		( RenamedHsBinds, RenamedMonoBinds, RenamedTyClDecl, RenamedHsPred )
17
import CmdLineOpts	( DynFlag(..) )
18

19
import TcRnMonad
20 21
import TcEnv		( tcGetInstEnv, tcSetInstEnv, newDFunName, 
			  InstInfo(..), pprInstInfo, InstBindings(..),
22
			  pprInstInfoDetails, tcLookupTyCon, tcExtendTyVarEnv
23
			)
24
import TcGenDeriv	-- Deriv stuff
25
import InstEnv		( InstEnv, simpleDFunClassTyCon, extendInstEnv )
26
import TcMonoType	( tcHsPred )
27
import TcSimplify	( tcSimplifyDeriv )
28

29
import RnBinds		( rnMethodBinds, rnTopMonoBinds )
30 31 32
import RnEnv		( bindLocalsFVRn )
import TcRnMonad		( thenM, returnM, mapAndUnzipM )
import HscTypes		( DFunId )
33

34
import BasicTypes	( NewOrData(..) )
35
import Class		( className, classArity, classKey, classTyVars, classSCTheta, Class )
36
import Subst		( mkTyVarSubst, substTheta )
37
import ErrUtils		( dumpIfSet_dyn )
38
import MkId		( mkDictFunId )
39
import DataCon		( dataConRepArgTys, dataConOrigArgTys, isNullaryDataCon, isExistentialDataCon )
40
import Maybes		( maybeToBool, catMaybes )
41
import Name		( Name, getSrcLoc, nameUnique )
42
import NameSet
43
import RdrName		( RdrName )
44

45
import TyCon		( tyConTyVars, tyConDataCons, tyConArity, 
sof's avatar
sof committed
46
			  tyConTheta, maybeTyConSingleCon, isDataTyCon,
47
			  isEnumerationTyCon, isRecursiveTyCon, TyCon
48
			)
49 50
import TcType		( TcType, ThetaType, mkTyVarTys, mkTyConApp, getClassPredTys_maybe,
			  isUnLiftedType, mkClassPred, tyVarsOfTypes, tcSplitFunTys, 
51
			  tcEqTypes, tcSplitAppTys, mkAppTys )
52 53
import Var		( TyVar, tyVarKind )
import VarSet		( mkVarSet, subVarSet )
54
import PrelNames
sof's avatar
sof committed
55
import Util		( zipWithEqual, sortLt, notNull )
56
import ListSetOps	( removeDups,  assoc )
57
import Outputable
58 59 60 61 62 63 64 65 66 67
\end{code}

%************************************************************************
%*									*
\subsection[TcDeriv-intro]{Introduction to how we do deriving}
%*									*
%************************************************************************

Consider

68 69
	data T a b = C1 (Foo a) (Bar b)
		   | C2 Int (T b a)
70 71 72
		   | C3 (T a a)
		   deriving (Eq)

73 74 75 76
[NOTE: See end of these comments for what to do with 
	data (C a, D b) => T a b = ...
]

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
We want to come up with an instance declaration of the form

	instance (Ping a, Pong b, ...) => Eq (T a b) where
		x == y = ...

It is pretty easy, albeit tedious, to fill in the code "...".  The
trick is to figure out what the context for the instance decl is,
namely @Ping@, @Pong@ and friends.

Let's call the context reqd for the T instance of class C at types
(a,b, ...)  C (T a b).  Thus:

	Eq (T a b) = (Ping a, Pong b, ...)

Now we can get a (recursive) equation from the @data@ decl:

	Eq (T a b) = Eq (Foo a) u Eq (Bar b)	-- From C1
		   u Eq (T b a) u Eq Int	-- From C2
		   u Eq (T a a)			-- From C3

Foo and Bar may have explicit instances for @Eq@, in which case we can
just substitute for them.  Alternatively, either or both may have
their @Eq@ instances given by @deriving@ clauses, in which case they
form part of the system of equations.

Now all we need do is simplify and solve the equations, iterating to
find the least fixpoint.  Notice that the order of the arguments can
switch around, as here in the recursive calls to T.

Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.

We start with:

	Eq (T a b) = {}		-- The empty set

Next iteration:
	Eq (T a b) = Eq (Foo a) u Eq (Bar b)	-- From C1
		   u Eq (T b a) u Eq Int	-- From C2
		   u Eq (T a a)			-- From C3

	After simplification:
		   = Eq a u Ping b u {} u {} u {}
		   = Eq a u Ping b

Next iteration:

	Eq (T a b) = Eq (Foo a) u Eq (Bar b)	-- From C1
		   u Eq (T b a) u Eq Int	-- From C2
		   u Eq (T a a)			-- From C3

	After simplification:
128
		   = Eq a u Ping b
129 130
		   u (Eq b u Ping a)
		   u (Eq a u Ping a)
131

132 133 134 135 136 137 138 139 140 141 142 143 144
		   = Eq a u Ping b u Eq b u Ping a

The next iteration gives the same result, so this is the fixpoint.  We
need to make a canonical form of the RHS to ensure convergence.  We do
this by simplifying the RHS to a form in which

	- the classes constrain only tyvars
	- the list is sorted by tyvar (major key) and then class (minor key)
	- no duplicates, of course

So, here are the synonyms for the ``equation'' structures:

\begin{code}
145 146 147
type DerivEqn = (Name, Class, TyCon, [TyVar], DerivRhs)
		-- The Name is the name for the DFun we'll build
		-- The tyvars bind all the variables in the RHS
148

149 150 151
pprDerivEqn (n,c,tc,tvs,rhs)
  = parens (hsep [ppr n, ppr c, ppr tc, ppr tvs] <+> equals <+> ppr rhs)

152
type DerivRhs  = ThetaType
153 154 155
type DerivSoln = DerivRhs
\end{code}

156

157 158
[Data decl contexts] A note about contexts on data decls
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
Consider

	data (RealFloat a) => Complex a = !a :+ !a deriving( Read )

We will need an instance decl like:

	instance (Read a, RealFloat a) => Read (Complex a) where
	  ...

The RealFloat in the context is because the read method for Complex is bound
to construct a Complex, and doing that requires that the argument type is
in RealFloat. 

But this ain't true for Show, Eq, Ord, etc, since they don't construct
a Complex; they only take them apart.

Our approach: identify the offending classes, and add the data type
context to the instance decl.  The "offending classes" are

	Read, Enum?

180 181 182 183 184 185
FURTHER NOTE ADDED March 2002.  In fact, Haskell98 now requires that
pattern matching against a constructor from a data type with a context
gives rise to the constraints for that context -- or at least the thinned
version.  So now all classes are "offending".


186

187 188 189 190 191 192 193
%************************************************************************
%*									*
\subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
%*									*
%************************************************************************

\begin{code}
194
tcDeriving  :: [RenamedTyClDecl]	-- All type constructors
195
	    -> TcM ([InstInfo],		-- The generated "instance decls".
196 197
		    RenamedHsBinds,	-- Extra generated bindings
		    FreeVars)		-- These are free in the generated bindings
198

199 200 201 202
tcDeriving tycl_decls
  = recoverM (returnM ([], EmptyBinds, emptyFVs)) $
    getDOpts			`thenM` \ dflags ->
    tcGetInstEnv		`thenM` \ inst_env ->
203 204

  	-- Fish the "deriving"-related information out of the TcEnv
205
	-- and make the necessary "equations".
206
    makeDerivEqns tycl_decls		    		`thenM` \ (ordinary_eqns, newtype_inst_info) ->
207
    let
208 209 210 211 212
	-- Add the newtype-derived instances to the inst env
	-- before tacking the "ordinary" ones
	inst_env1 = extend_inst_env dflags inst_env 
				    (map iDFunId newtype_inst_info)
    in    
213
    deriveOrdinaryStuff inst_env1 ordinary_eqns		`thenM` \ (ordinary_inst_info, binds, fvs) ->
214 215
    let
	inst_info  = newtype_inst_info ++ ordinary_inst_info
216 217
    in

218 219
    ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances" 
	     (ddump_deriving inst_info binds))		`thenM_`
220

221
    returnM (inst_info, binds, fvs)
222 223 224 225

  where
    ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
    ddump_deriving inst_infos extra_binds
226
      = vcat (map ppr_info inst_infos) $$ ppr extra_binds
227

228
    ppr_info inst_info = pprInstInfo inst_info $$ 
229
			 nest 4 (pprInstInfoDetails inst_info)
230
	-- pprInstInfo doesn't print much: only the type
231

232
-----------------------------------------
233 234
deriveOrdinaryStuff inst_env_in []	-- Short cut
  = returnM ([], EmptyBinds, emptyFVs)
235

236
deriveOrdinaryStuff inst_env_in eqns
237
  =	-- Take the equation list and solve it, to deliver a list of
238 239
	-- solutions, a.k.a. the contexts for the instance decls
	-- required for the corresponding equations.
240
    solveDerivEqns inst_env_in eqns	    	`thenM` \ new_dfuns ->
241 242 243 244

	-- Now augment the InstInfos, adding in the rather boring
	-- actual-code-to-do-the-methods binds.  We may also need to
	-- generate extra not-one-inst-decl-specific binds, notably
245
	-- "con2tag" and/or "tag2con" functions.  We do these
246
	-- separately.
247
    gen_taggery_Names new_dfuns		`thenM` \ nm_alist_etc ->
248 249 250 251

    let
	extra_mbind_list = map gen_tag_n_con_monobind nm_alist_etc
	extra_mbinds     = foldr AndMonoBinds EmptyMonoBinds extra_mbind_list
252 253 254
	mbinders	 = collectMonoBinders extra_mbinds
    in
    mappM gen_bind new_dfuns		`thenM` \ method_binds_s ->
255
	
256 257 258
    traceTc (text "tcDeriv" <+> ppr method_binds_s)	`thenM_`
    getModule						`thenM` \ this_mod ->
    initRn (InterfaceMode this_mod) (
259
	-- Rename to get RenamedBinds.
260 261 262 263 264 265 266 267 268
	-- The only tricky bit is that the extra_binds must scope 
	-- over the method bindings for the instances.
	bindLocalsFVRn (ptext (SLIT("deriving"))) mbinders	$ \ _ ->
	rnTopMonoBinds extra_mbinds []			`thenM` \ (rn_extra_binds, fvs) ->
	mapAndUnzipM rn_meths method_binds_s		`thenM` \ (rn_method_binds_s, fvs_s) ->
	returnM ((rn_method_binds_s, rn_extra_binds), 
		  fvs `plusFV` plusFVs fvs_s)
    )				`thenM` \ ((rn_method_binds_s, rn_extra_binds), fvs) ->
    let
269
	new_inst_infos = zipWith gen_inst_info new_dfuns rn_method_binds_s
270
    in
271
    returnM (new_inst_infos, rn_extra_binds, fvs)
272

273
  where
274
	-- Make a Real dfun instead of the dummy one we have so far
275 276
    gen_inst_info :: DFunId -> RenamedMonoBinds -> InstInfo
    gen_inst_info dfun binds
277
      = InstInfo { iDFunId = dfun, iBinds = VanillaInst binds [] }
278

279
    rn_meths (cls, meths) = rnMethodBinds cls [] meths
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
\end{code}


%************************************************************************
%*									*
\subsection[TcDeriv-eqns]{Forming the equations}
%*									*
%************************************************************************

@makeDerivEqns@ fishes around to find the info about needed derived
instances.  Complicating factors:
\begin{itemize}
\item
We can only derive @Enum@ if the data type is an enumeration
type (all nullary data constructors).

\item
We can only derive @Ix@ if the data type is an enumeration {\em
or} has just one data constructor (e.g., tuples).
\end{itemize}

[See Appendix~E in the Haskell~1.2 report.] This code here deals w/
all those.

\begin{code}
305 306 307
makeDerivEqns :: [RenamedTyClDecl] 
	      -> TcM ([DerivEqn],	-- Ordinary derivings
		      [InstInfo])	-- Special newtype derivings
308

309
makeDerivEqns tycl_decls
310 311
  = mapAndUnzipM mk_eqn derive_these	 	`thenM` \ (maybe_ordinaries, maybe_newtypes) ->
    returnM (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
312 313
  where
    ------------------------------------------------------------------
314 315
    derive_these :: [(NewOrData, Name, RenamedHsPred)]
	-- Find the (nd, TyCon, Pred) pairs that must be `derived'
316
	-- NB: only source-language decls have deriving, no imported ones do
317 318 319
    derive_these = [ (nd, tycon, pred) 
		   | TyData {tcdND = nd, tcdName = tycon, tcdDerivs = Just preds} <- tycl_decls,
		     pred <- preds ]
320 321

    ------------------------------------------------------------------
322
    mk_eqn :: (NewOrData, Name, RenamedHsPred) -> TcM (Maybe DerivEqn, Maybe InstInfo)
323
	-- We swizzle the tyvars and datacons out of the tycon
324 325
	-- to make the rest of the equation

326
    mk_eqn (new_or_data, tycon_name, pred)
327 328 329
      = tcLookupTyCon tycon_name		`thenM` \ tycon ->
	addSrcLoc (getSrcLoc tycon)		$
        addErrCtxt (derivCtxt Nothing tycon)	$
330 331
	tcExtendTyVarEnv (tyConTyVars tycon)	$	-- Deriving preds may (now) mention
							-- the type variables for the type constructor
332
        tcHsPred pred				`thenM` \ pred' ->
333 334 335
	case getClassPredTys_maybe pred' of
	   Nothing 	    -> bale_out (malformedPredErr tycon pred)
	   Just (clas, tys) -> mk_eqn_help new_or_data tycon clas tys
336

337 338 339 340 341
    ------------------------------------------------------------------
    mk_eqn_help DataType tycon clas tys
      | Just err <- chk_out clas tycon tys
      = bale_out (derivingThingErr clas tys tycon tyvars err)
      | otherwise 
342 343
      = new_dfun_name clas tycon	 `thenM` \ dfun_name ->
	returnM (Just (dfun_name, clas, tycon, tyvars, constraints), Nothing)
344 345 346 347 348 349
      where
	tyvars    = tyConTyVars tycon
	data_cons = tyConDataCons tycon
	constraints = extra_constraints ++ 
	  	      [ mkClassPred clas [arg_ty] 
		      | data_con <- tyConDataCons tycon,
350
		        arg_ty   <- dataConRepArgTys data_con,		-- dataConOrigArgTys???
351 352 353 354 355
				-- Use the same type variables
				-- as the type constructor,
				-- hence no need to instantiate
			not (isUnLiftedType arg_ty)	-- No constraints for unlifted types?
		      ]
356

357
	 -- "extra_constraints": see note [Data decl contexts] above
358 359
	extra_constraints = tyConTheta tycon

360
    mk_eqn_help NewType tycon clas tys
361
      =	doptM Opt_GlasgowExts			`thenM` \ gla_exts ->
362 363
        if can_derive_via_isomorphism && (gla_exts || standard_instance) then
		-- Go ahead and use the isomorphism
364
	   traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)	`thenM_`
365
       	   new_dfun_name clas tycon  		`thenM` \ dfun_name ->
366 367
	   returnM (Nothing, Just (InstInfo { iDFunId = mk_dfun dfun_name,
					      iBinds = NewTypeDerived rep_tys }))
368 369 370 371 372
	else
	   if standard_instance then
		mk_eqn_help DataType tycon clas []	-- Go via bale-out route
	   else
	   	bale_out cant_derive_err
373 374
      where
	-- Here is the plan for newtype derivings.  We see
375 376 377
	--	  newtype T a1...an = T (t ak...an) deriving (.., C s1 .. sm, ...)
	-- where aj...an do not occur free in t, and the (C s1 ... sm) is a 
	-- *partial applications* of class C with the last parameter missing
378 379
	--
	-- We generate the instances
380
	--	 instance C s1 .. sm (t ak...aj) => C s1 .. sm (T a1...aj)
381 382 383
	-- where T a1...aj is the partial application of the LHS of the correct kind
	--
	-- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
384 385
	--	instance Monad (ST s) => Monad (T s) where 
	--	  fail = coerce ... (fail @ ST s)
386

387 388
	clas_tyvars = classTyVars clas
	kind = tyVarKind (last clas_tyvars)
389 390
		-- Kind of the thing we want to instance
		--   e.g. argument kind of Monad, *->*
391

392 393 394 395 396
	(arg_kinds, _) = tcSplitFunTys kind
	n_args_to_drop = length arg_kinds	
		-- Want to drop 1 arg from (T s a) and (ST s a)
		-- to get 	instance Monad (ST s) => Monad (T s)

397 398 399 400 401 402 403 404 405 406 407 408
	-- Note [newtype representation]
	-- We must not use newTyConRep to get the representation 
	-- type, because that looks through all intermediate newtypes
	-- To get the RHS of *this* newtype, just look at the data
	-- constructor.  For example
	--	newtype B = MkB Int
	--	newtype A = MkA B deriving( Num )
	-- We want the Num instance of B, *not* the Num instance of Int,
	-- when making the Num instance of A!
	tyvars 		      = tyConTyVars tycon
        rep_ty 		      = head (dataConOrigArgTys (head (tyConDataCons tycon)))
	(rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
409 410

	n_tyvars_to_keep = tyConArity tycon  - n_args_to_drop
411 412
	tyvars_to_drop   = drop n_tyvars_to_keep tyvars
	tyvars_to_keep   = take n_tyvars_to_keep tyvars
413

414
	n_args_to_keep = length rep_ty_args - n_args_to_drop
415 416
	args_to_drop   = drop n_args_to_keep rep_ty_args
 	args_to_keep   = take n_args_to_keep rep_ty_args
417

418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
	rep_tys  = tys ++ [mkAppTys rep_fn args_to_keep]
	rep_pred = mkClassPred clas rep_tys
		-- rep_pred is the representation dictionary, from where
		-- we are gong to get all the methods for the newtype dictionary

	inst_tys = (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)])
		-- The 'tys' here come from the partial application
		-- in the deriving clause. The last arg is the new
		-- instance type.

		-- We must pass the superclasses; the newtype might be an instance
		-- of them in a different way than the representation type
		-- E.g.		newtype Foo a = Foo a deriving( Show, Num, Eq )
		-- Then the Show instance is not done via isomprphism; it shows
		-- 	Foo 3 as "Foo 3"
		-- The Num instance is derived via isomorphism, but the Show superclass
		-- dictionary must the Show instance for Foo, *not* the Show dictionary
		-- gotten from the Num dictionary. So we must build a whole new dictionary
		-- not just use the Num one.  The instance we want is something like:
		--	instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
		--		(+) = ((+)@a)
		--		...etc...
		-- There's no 'corece' needed because after the type checker newtypes
		-- are transparent.

	sc_theta = substTheta (mkTyVarSubst clas_tyvars inst_tys)
			      (classSCTheta clas)

		-- If there are no tyvars, there's no need
		-- to abstract over the dictionaries we need
	dict_args | null tyvars = []
		  | otherwise   = rep_pred : sc_theta

		-- Finally! Here's where we build the dictionary Id
	mk_dfun dfun_name = mkDictFunId dfun_name tyvars dict_args clas inst_tys

	-------------------------------------------------------------------
	--  Figuring out whether we can only do this newtype-deriving thing
456

457 458 459 460 461
	standard_instance = null tys && classKey clas `elem` derivableClassKeys

	can_derive_via_isomorphism
	   =  not (clas `hasKey` readClassKey)	-- Never derive Read,Show this way
	   && not (clas `hasKey` showClassKey)
462 463 464
	   && length tys + 1 == classArity clas	-- Well kinded;
						-- eg not: newtype T ... deriving( ST )
						--	because ST needs *2* type params
465 466 467 468 469
	   && n_tyvars_to_keep >= 0		-- Well kinded; 
						-- eg not: newtype T = T Int deriving( Monad )
	   && n_args_to_keep   >= 0		-- Well kinded: 
						-- eg not: newtype T a = T Int deriving( Monad )
	   && eta_ok				-- Eta reduction works
470 471 472 473
	   && not (isRecursiveTyCon tycon)	-- Does not work for recursive tycons:
						--	newtype A = MkA [A]
						-- Don't want
						--	instance Eq [A] => Eq A !!
474 475 476 477 478 479 480

	-- Check that eta reduction is OK
	-- 	(a) the dropped-off args are identical
	--	(b) the remaining type args mention 
	--	    only the remaining type variables
	eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
	      && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep) 
481 482

	cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
483
				(vcat [ptext SLIT("too hard for cunning newtype deriving"),
484 485
				       ptext SLIT("debug info:") <+> ppr n_tyvars_to_keep <+>
					ppr n_args_to_keep <+> ppr eta_ok <+>
486 487
					ppr (isRecursiveTyCon tycon)
				      ])
488

489
    bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing) 
490 491

    ------------------------------------------------------------------
492
    chk_out :: Class -> TyCon -> [TcType] -> Maybe SDoc
493
    chk_out clas tycon tys
494
	| notNull tys						        = Just ty_args_why
495 496 497 498 499 500 501
	| not (getUnique clas `elem` derivableClassKeys)		= Just non_std_why
	| clas `hasKey` enumClassKey    && not is_enumeration 	        = Just nullary_why
	| clas `hasKey` boundedClassKey && not is_enumeration_or_single = Just single_nullary_why
	| clas `hasKey` ixClassKey      && not is_enumeration_or_single = Just single_nullary_why
	| null data_cons		    			 	= Just no_cons_why
	| any isExistentialDataCon data_cons 				= Just existential_why     
	| otherwise			     				= Nothing
502
	where
503
	    data_cons = tyConDataCons tycon
504 505 506 507
	    is_enumeration = isEnumerationTyCon tycon
	    is_single_con  = maybeToBool (maybeTyConSingleCon tycon)
	    is_enumeration_or_single = is_enumeration || is_single_con

508 509 510 511 512 513 514 515
	    single_nullary_why = ptext SLIT("one constructor data type or type with all nullary constructors expected")
	    nullary_why        = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
	    no_cons_why	       = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
	    ty_args_why	       = quotes (ppr pred) <+> ptext SLIT("is not a class")
   	    non_std_why	       = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
	    existential_why    = quotes (ppr tycon) <+> ptext SLIT("has existentially-quantified constructor(s)")

	    pred = mkClassPred clas tys
516

517 518 519 520
new_dfun_name clas tycon 	-- Just a simple wrapper
  = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
	-- The type passed to newDFunName is only used to generate
	-- a suitable string; hence the empty type arg list
521 522 523 524 525 526 527 528
\end{code}

%************************************************************************
%*									*
\subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
%*									*
%************************************************************************

529
A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
530 531 532 533
terms, which is the final correct RHS for the corresponding original
equation.
\begin{itemize}
\item
534
Each (k,TyVarTy tv) in a solution constrains only a type
535 536 537
variable, tv.

\item
538
The (k,TyVarTy tv) pairs in a solution are canonically
539 540 541 542 543
ordered by sorting on type varible, tv, (major key) and then class, k,
(minor key)
\end{itemize}

\begin{code}
544
solveDerivEqns :: InstEnv
545
	       -> [DerivEqn]
546 547
	       -> TcM [DFunId]	-- Solns in same order as eqns.
				-- This bunch is Absolutely minimal...
548

549
solveDerivEqns inst_env_in orig_eqns
550
  = iterateDeriv 1 initial_solutions
551 552 553 554 555 556 557
  where
	-- The initial solutions for the equations claim that each
	-- instance has an empty context; this solution is certainly
	-- in canonical form.
    initial_solutions :: [DerivSoln]
    initial_solutions = [ [] | _ <- orig_eqns ]

558
    ------------------------------------------------------------------
559 560 561
	-- iterateDeriv calculates the next batch of solutions,
	-- compares it with the current one; finishes if they are the
	-- same, otherwise recurses with the new solutions.
562
	-- It fails if any iteration fails
563 564 565 566 567 568 569 570
    iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
    iterateDeriv n current_solns
      | n > 20 	-- Looks as if we are in an infinite loop
		-- This can happen if we have -fallow-undecidable-instances
		-- (See TcSimplify.tcSimplifyDeriv.)
      = pprPanic "solveDerivEqns: probable loop" 
		 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
      | otherwise
571
      =	getDOpts				`thenM` \ dflags ->
572 573 574 575
        let 
	    dfuns    = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
	    inst_env = extend_inst_env dflags inst_env_in dfuns
        in
576
        checkNoErrs (
577 578 579
		  -- Extend the inst info from the explicit instance decls
		  -- with the current set of solutions, and simplify each RHS
	    tcSetInstEnv inst_env $
580 581
	    mappM gen_soln orig_eqns
	)				`thenM` \ new_solns ->
582
	if (current_solns == new_solns) then
583
	    returnM dfuns
584
	else
585
	    iterateDeriv (n+1) new_solns
586 587

    ------------------------------------------------------------------
588 589

    gen_soln (_, clas, tc,tyvars,deriv_rhs)
590 591 592 593
      = addSrcLoc (getSrcLoc tc)		$
	addErrCtxt (derivCtxt (Just clas) tc)	$
	tcSimplifyDeriv tyvars deriv_rhs	`thenM` \ theta ->
	returnM (sortLt (<) theta)	-- Canonicalise before returning the soluction
594 595 596
\end{code}

\begin{code}
597 598 599 600
extend_inst_env dflags inst_env new_dfuns
  = new_inst_env
  where
    (new_inst_env, _errs) = extendInstEnv dflags inst_env new_dfuns
601 602 603 604
	-- Ignore the errors about duplicate instances.
	-- We don't want repeated error messages
	-- They'll appear later, when we do the top-level extendInstEnvs

605
mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
606 607
  = mkDictFunId dfun_name tyvars theta
		clas [mkTyConApp tycon (mkTyVarTys tyvars)] 
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
\end{code}

%************************************************************************
%*									*
\subsection[TcDeriv-normal-binds]{Bindings for the various classes}
%*									*
%************************************************************************

After all the trouble to figure out the required context for the
derived instance declarations, all that's left is to chug along to
produce them.  They will then be shoved into @tcInstDecls2@, which
will do all its usual business.

There are lots of possibilities for code to generate.  Here are
various general remarks.

PRINCIPLES:
\begin{itemize}
\item
We want derived instances of @Eq@ and @Ord@ (both v common) to be
``you-couldn't-do-better-by-hand'' efficient.

\item
631
Deriving @Show@---also pretty common--- should also be reasonable good code.
632 633 634 635 636 637 638 639 640

\item
Deriving for the other classes isn't that common or that big a deal.
\end{itemize}

PRAGMATICS:

\begin{itemize}
\item
641
Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
642 643

\item
644
Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
645 646

\item
647
We {\em normally} generate code only for the non-defaulted methods;
648 649 650 651 652 653 654 655 656 657 658
there are some exceptions for @Eq@ and (especially) @Ord@...

\item
Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
constructor's numeric (@Int#@) tag.  These are generated by
@gen_tag_n_con_binds@, and the heuristic for deciding if one of
these is around is given by @hasCon2TagFun@.

The examples under the different sections below will make this
clearer.

659 660 661 662
\item
Much less often (really just for deriving @Ix@), we use a
@_tag2con_<tycon>@ function.  See the examples.

663
\item
664
We use the renamer!!!  Reason: we're supposed to be
665 666 667
producing @RenamedMonoBinds@ for the methods, but that means
producing correctly-uniquified code on the fly.  This is entirely
possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
668
So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
669 670 671 672
the renamer.  What a great hack!
\end{itemize}

\begin{code}
673
-- Generate the method bindings for the required instance
674 675
-- (paired with class name, as we need that when renaming
--  the method binds)
676 677 678 679
gen_bind :: DFunId -> TcM (Name, RdrNameMonoBinds)
gen_bind dfun
  = getFixityEnv		`thenM` \ fix_env -> 
    returnM (cls_nm, gen_binds_fn fix_env cls_nm tycon)
680
  where
681
    cls_nm	  = className clas
682
    (clas, tycon) = simpleDFunClassTyCon dfun
683

684 685 686 687
gen_binds_fn fix_env cls_nm
  = assoc "gen_bind:bad derived class"
	  gen_list (nameUnique cls_nm)
  where
688 689 690 691 692
    gen_list = [(eqClassKey,      gen_Eq_binds)
	       ,(ordClassKey,     gen_Ord_binds)
	       ,(enumClassKey,    gen_Enum_binds)
	       ,(boundedClassKey, gen_Bounded_binds)
	       ,(ixClassKey,      gen_Ix_binds)
693 694
	       ,(showClassKey,    gen_Show_binds fix_env)
	       ,(readClassKey,    gen_Read_binds fix_env)
695
	       ]
696 697
\end{code}

698

699 700
%************************************************************************
%*									*
701
\subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
702 703 704
%*									*
%************************************************************************

705

706 707 708
data Foo ... = ...

con2tag_Foo :: Foo ... -> Int#
709
tag2con_Foo :: Int -> Foo ...	-- easier if Int, not Int#
710
maxtag_Foo  :: Int		-- ditto (NB: not unlifted)
711 712 713 714 715 716 717 718 719 720 721 722


We have a @con2tag@ function for a tycon if:
\begin{itemize}
\item
We're deriving @Eq@ and the tycon has nullary data constructors.

\item
Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
(enum type only????)
\end{itemize}

723 724 725 726 727 728 729 730
We have a @tag2con@ function for a tycon if:
\begin{itemize}
\item
We're deriving @Enum@, or @Ix@ (enum type only???)
\end{itemize}

If we have a @tag2con@ function, we also generate a @maxtag@ constant.

731
\begin{code}
732
gen_taggery_Names :: [DFunId]
733
		  -> TcM [(RdrName,	-- for an assoc list
734 735
		  	   TyCon,	-- related tycon
			   TagThingWanted)]
736

737
gen_taggery_Names dfuns
738 739
  = foldlM do_con2tag []           tycons_of_interest `thenM` \ names_so_far ->
    foldlM do_tag2con names_so_far tycons_of_interest
740
  where
741
    all_CTs = map simpleDFunClassTyCon dfuns
742
    all_tycons		    = map snd all_CTs
743
    (tycons_of_interest, _) = removeDups compare all_tycons
744
    
745
    do_con2tag acc_Names tycon
sof's avatar
sof committed
746
      | isDataTyCon tycon &&
sof's avatar
sof committed
747
        ((we_are_deriving eqClassKey tycon
748
	    && any isNullaryDataCon (tyConDataCons tycon))
sof's avatar
sof committed
749
	 || (we_are_deriving ordClassKey  tycon
750
	    && not (maybeToBool (maybeTyConSingleCon tycon)))
sof's avatar
sof committed
751
	 || (we_are_deriving enumClassKey tycon)
sof's avatar
sof committed
752
	 || (we_are_deriving ixClassKey   tycon))
sof's avatar
sof committed
753
	
754
      = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
755
		   : acc_Names)
sof's avatar
sof committed
756
      | otherwise
757
      = returnM acc_Names
758

759
    do_tag2con acc_Names tycon
sof's avatar
sof committed
760 761
      | isDataTyCon tycon &&
         (we_are_deriving enumClassKey tycon ||
762 763
	  we_are_deriving ixClassKey   tycon
	  && isEnumerationTyCon tycon)
764
      = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
765
		 : (maxtag_RDR  tycon, tycon, GenMaxTag)
sof's avatar
sof committed
766 767
		 : acc_Names)
      | otherwise
768
      = returnM acc_Names
769 770

    we_are_deriving clas_key tycon
771
      = is_in_eqns clas_key tycon all_CTs
772 773
      where
	is_in_eqns clas_key tycon [] = False
774
	is_in_eqns clas_key tycon ((c,t):cts)
775
	  =  (clas_key == classKey c && tycon == t)
776
	  || is_in_eqns clas_key tycon cts
777
\end{code}
778

779
\begin{code}
780 781
derivingThingErr clas tys tycon tyvars why
  = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
782
	 parens why]
783 784
  where
    pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
785

786
malformedPredErr tycon pred = ptext SLIT("Illegal deriving item") <+> ppr pred
787

788 789 790 791 792 793 794
derivCtxt :: Maybe Class -> TyCon -> SDoc
derivCtxt maybe_cls tycon
  = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
  where
    cls = case maybe_cls of
	    Nothing -> ptext SLIT("instances")
	    Just c  -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")
795
\end{code}
796