[project @ 1997-03-17 20:34:25 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcGenDeriv.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[TcGenDeriv]{Generating derived instance declarations}
5
6 This module is nominally ``subordinate'' to @TcDeriv@, which is the
7 ``official'' interface to deriving-related things.
8
9 This is where we do all the grimy bindings' generation.
10
11 \begin{code}
12 #include "HsVersions.h"
13
14 module TcGenDeriv (
15         gen_Bounded_binds,
16         gen_Enum_binds,
17         gen_Eval_binds,
18         gen_Eq_binds,
19         gen_Ix_binds,
20         gen_Ord_binds,
21         gen_Read_binds,
22         gen_Show_binds,
23         gen_tag_n_con_monobind,
24
25         con2tag_RDR, tag2con_RDR, maxtag_RDR,
26
27         TagThingWanted(..)
28     ) where
29
30 IMP_Ubiq()
31 IMPORT_1_3(List(partition))
32
33 import HsSyn            ( HsBinds(..), Bind(..), MonoBinds(..), Match(..), GRHSsAndBinds(..),
34                           GRHS(..), HsExpr(..), HsLit(..), InPat(..), Stmt(..), DoOrListComp(..),
35                           ArithSeqInfo, Sig, HsType, FixityDecl, Fixity, Fake )
36 import RdrHsSyn         ( RdrName(..), varQual, varUnqual, mkOpApp,
37                           SYN_IE(RdrNameMonoBinds), SYN_IE(RdrNameHsExpr), SYN_IE(RdrNamePat)
38                         )
39 -- import RnHsSyn               ( RenamedFixityDecl(..) )
40
41 import Id               ( GenId, dataConNumFields, isNullaryDataCon, dataConTag,
42                           dataConRawArgTys, fIRST_TAG,
43                           isDataCon, SYN_IE(DataCon), SYN_IE(ConTag) )
44 import Maybes           ( maybeToBool )
45 import Name             ( getOccString, getOccName, getSrcLoc, occNameString, modAndOcc, OccName, Name )
46
47 import PrimOp           ( PrimOp(..) )
48 import PrelInfo         -- Lots of RdrNames
49 import SrcLoc           ( mkGeneratedSrcLoc )
50 import TyCon            ( TyCon, tyConDataCons, isEnumerationTyCon, maybeTyConSingleCon )
51 import Type             ( eqTy, isPrimType )
52 import TysPrim          ( charPrimTy, intPrimTy, wordPrimTy, addrPrimTy,
53                           floatPrimTy, doublePrimTy
54                         )
55 import Util             ( mapAccumL, zipEqual, zipWith3Equal, nOfThem, panic, assertPanic )
56 \end{code}
57
58 %************************************************************************
59 %*                                                                      *
60 \subsection{Generating code, by derivable class}
61 %*                                                                      *
62 %************************************************************************
63
64 %************************************************************************
65 %*                                                                      *
66 \subsubsection{Generating @Eq@ instance declarations}
67 %*                                                                      *
68 %************************************************************************
69
70 Here are the heuristics for the code we generate for @Eq@:
71 \begin{itemize}
72 \item
73   Let's assume we have a data type with some (possibly zero) nullary
74   data constructors and some ordinary, non-nullary ones (the rest,
75   also possibly zero of them).  Here's an example, with both \tr{N}ullary
76   and \tr{O}rdinary data cons.
77 \begin{verbatim}
78 data Foo ... = N1 | N2 ... | Nn | O1 a b | O2 Int | O3 Double b b | ...
79 \end{verbatim}
80
81 \item
82   For the ordinary constructors (if any), we emit clauses to do The
83   Usual Thing, e.g.,:
84
85 \begin{verbatim}
86 (==) (O1 a1 b1)    (O1 a2 b2)    = a1 == a2 && b1 == b2
87 (==) (O2 a1)       (O2 a2)       = a1 == a2
88 (==) (O3 a1 b1 c1) (O3 a2 b2 c2) = a1 == a2 && b1 == b2 && c1 == c2
89 \end{verbatim}
90
91   Note: if we're comparing unboxed things, e.g., if \tr{a1} and
92   \tr{a2} are \tr{Float#}s, then we have to generate
93 \begin{verbatim}
94 case (a1 `eqFloat#` a2) of
95   r -> r
96 \end{verbatim}
97   for that particular test.
98
99 \item
100   If there are any nullary constructors, we emit a catch-all clause of
101   the form:
102
103 \begin{verbatim}
104 (==) a b  = case (con2tag_Foo a) of { a# ->
105             case (con2tag_Foo b) of { b# ->
106             case (a# ==# b#)     of {
107               r -> r
108             }}}
109 \end{verbatim}
110
111   If there aren't any nullary constructors, we emit a simpler
112   catch-all:
113 \begin{verbatim}
114 (==) a b  = False
115 \end{verbatim}
116
117 \item
118   For the @(/=)@ method, we normally just use the default method.
119
120   If the type is an enumeration type, we could/may/should? generate
121   special code that calls @con2tag_Foo@, much like for @(==)@ shown
122   above.
123
124 \item
125   We thought about doing this: If we're also deriving @Ord@ for this
126   tycon, we generate:
127 \begin{verbatim}
128 instance ... Eq (Foo ...) where
129   (==) a b  = case (compare a b) of { _LT -> False; _EQ -> True ; _GT -> False}
130   (/=) a b  = case (compare a b) of { _LT -> True ; _EQ -> False; _GT -> True }
131 \begin{verbatim}
132   However, that requires that \tr{Ord <whatever>} was put in the context
133   for the instance decl, which it probably wasn't, so the decls
134   produced don't get through the typechecker.
135 \end{itemize}
136
137 \begin{code}
138 gen_Eq_binds :: TyCon -> RdrNameMonoBinds
139
140 gen_Eq_binds tycon
141   = let
142         tycon_loc = getSrcLoc tycon
143         (nullary_cons, nonnullary_cons)
144           = partition isNullaryDataCon (tyConDataCons tycon)
145
146         rest
147           = if (null nullary_cons) then
148                 case maybeTyConSingleCon tycon of
149                   Just _ -> []
150                   Nothing -> -- if cons don't match, then False
151                      [([a_Pat, b_Pat], false_Expr)]
152             else -- calc. and compare the tags
153                  [([a_Pat, b_Pat],
154                     untag_Expr tycon [(a_RDR,ah_RDR), (b_RDR,bh_RDR)]
155                       (cmp_tags_Expr eqH_Int_RDR ah_RDR bh_RDR true_Expr false_Expr))]
156     in
157     mk_FunMonoBind tycon_loc eq_RDR ((map pats_etc nonnullary_cons) ++ rest)
158             `AndMonoBinds`
159     mk_easy_FunMonoBind tycon_loc ne_RDR [a_Pat, b_Pat] [] (
160         HsApp (HsVar not_RDR) (HsPar (mk_easy_App eq_RDR [a_RDR, b_RDR])))
161   where
162     ------------------------------------------------------------------
163     pats_etc data_con
164       = let
165             con1_pat = ConPatIn data_con_RDR (map VarPatIn as_needed)
166             con2_pat = ConPatIn data_con_RDR (map VarPatIn bs_needed)
167
168             data_con_RDR = qual_orig_name data_con
169             con_arity   = length tys_needed
170             as_needed   = take con_arity as_RDRs
171             bs_needed   = take con_arity bs_RDRs
172             tys_needed  = dataConRawArgTys data_con
173         in
174         ([con1_pat, con2_pat], nested_eq_expr tys_needed as_needed bs_needed)
175       where
176         nested_eq_expr []  [] [] = true_Expr
177         nested_eq_expr tys as bs
178           = foldl1 and_Expr (zipWith3Equal "nested_eq" nested_eq tys as bs)
179           where
180             nested_eq ty a b = HsPar (eq_Expr ty (HsVar a) (HsVar b))
181 \end{code}
182
183 %************************************************************************
184 %*                                                                      *
185 \subsubsection{Generating @Ord@ instance declarations}
186 %*                                                                      *
187 %************************************************************************
188
189 For a derived @Ord@, we concentrate our attentions on @compare@
190 \begin{verbatim}
191 compare :: a -> a -> Ordering
192 data Ordering = LT | EQ | GT deriving ()
193 \end{verbatim}
194
195 We will use the same example data type as above:
196 \begin{verbatim}
197 data Foo ... = N1 | N2 ... | Nn | O1 a b | O2 Int | O3 Double b b | ...
198 \end{verbatim}
199
200 \begin{itemize}
201 \item
202   We do all the other @Ord@ methods with calls to @compare@:
203 \begin{verbatim}
204 instance ... (Ord <wurble> <wurble>) where
205     a <  b  = case (compare a b) of { LT -> True;  EQ -> False; GT -> False }
206     a <= b  = case (compare a b) of { LT -> True;  EQ -> True;  GT -> False }
207     a >= b  = case (compare a b) of { LT -> False; EQ -> True;  GT -> True  }
208     a >  b  = case (compare a b) of { LT -> False; EQ -> False; GT -> True  }
209
210     max a b = case (compare a b) of { LT -> b; EQ -> a;  GT -> a }
211     min a b = case (compare a b) of { LT -> a; EQ -> b;  GT -> b }
212
213     -- compare to come...
214 \end{verbatim}
215
216 \item
217   @compare@ always has two parts.  First, we use the compared
218   data-constructors' tags to deal with the case of different
219   constructors:
220 \begin{verbatim}
221 compare a b = case (con2tag_Foo a) of { a# ->
222               case (con2tag_Foo b) of { b# ->
223               case (a# ==# b#)     of {
224                True  -> cmp_eq a b
225                False -> case (a# <# b#) of
226                          True  -> _LT
227                          False -> _GT
228               }}}
229   where
230     cmp_eq = ... to come ...
231 \end{verbatim}
232
233 \item
234   We are only left with the ``help'' function @cmp_eq@, to deal with
235   comparing data constructors with the same tag.
236
237   For the ordinary constructors (if any), we emit the sorta-obvious
238   compare-style stuff; for our example:
239 \begin{verbatim}
240 cmp_eq (O1 a1 b1) (O1 a2 b2)
241   = case (compare a1 a2) of { LT -> LT; EQ -> compare b1 b2; GT -> GT }
242
243 cmp_eq (O2 a1) (O2 a2)
244   = compare a1 a2
245
246 cmp_eq (O3 a1 b1 c1) (O3 a2 b2 c2)
247   = case (compare a1 a2) of {
248       LT -> LT;
249       GT -> GT;
250       EQ -> case compare b1 b2 of {
251               LT -> LT;
252               GT -> GT;
253               EQ -> compare c1 c2
254             }
255     }
256 \end{verbatim}
257
258   Again, we must be careful about unboxed comparisons.  For example,
259   if \tr{a1} and \tr{a2} were \tr{Int#}s in the 2nd example above, we'd need to
260   generate:
261 \begin{verbatim}
262 cmp_eq lt eq gt (O2 a1) (O2 a2)
263   = compareInt# a1 a2
264   -- or maybe the unfolded equivalent
265 \end{verbatim}
266
267 \item
268   For the remaining nullary constructors, we already know that the
269   tags are equal so:
270 \begin{verbatim}
271 cmp_eq _ _ = EQ
272 \end{verbatim}
273 \end{itemize}
274
275 \begin{code}
276 gen_Ord_binds :: TyCon -> RdrNameMonoBinds
277
278 gen_Ord_binds tycon
279   = defaulted `AndMonoBinds` compare
280   where
281     tycon_loc = getSrcLoc tycon
282     --------------------------------------------------------------------
283     compare = mk_easy_FunMonoBind tycon_loc compare_RDR
284                 [a_Pat, b_Pat]
285                 [cmp_eq]
286             (if maybeToBool (maybeTyConSingleCon tycon) then
287                 cmp_eq_Expr ltTag_Expr eqTag_Expr gtTag_Expr a_Expr b_Expr
288              else
289                 untag_Expr tycon [(a_RDR, ah_RDR), (b_RDR, bh_RDR)]
290                   (cmp_tags_Expr eqH_Int_RDR ah_RDR bh_RDR
291                         -- True case; they are equal
292                         -- If an enumeration type we are done; else
293                         -- recursively compare their components
294                     (if isEnumerationTyCon tycon then
295                         eqTag_Expr
296                      else
297                         cmp_eq_Expr ltTag_Expr eqTag_Expr gtTag_Expr a_Expr b_Expr
298                     )
299                         -- False case; they aren't equal
300                         -- So we need to do a less-than comparison on the tags
301                     (cmp_tags_Expr ltH_Int_RDR ah_RDR bh_RDR ltTag_Expr gtTag_Expr)))
302
303     (nullary_cons, nonnullary_cons)
304       = partition isNullaryDataCon (tyConDataCons tycon)
305
306     cmp_eq
307       = mk_FunMonoBind tycon_loc cmp_eq_RDR (map pats_etc nonnullary_cons ++
308                                              [([WildPatIn, WildPatIn], default_rhs)])
309       where
310         pats_etc data_con
311           = ([con1_pat, con2_pat],
312              nested_compare_expr tys_needed as_needed bs_needed)
313           where
314             con1_pat = ConPatIn data_con_RDR (map VarPatIn as_needed)
315             con2_pat = ConPatIn data_con_RDR (map VarPatIn bs_needed)
316
317             data_con_RDR = qual_orig_name data_con
318             con_arity   = length tys_needed
319             as_needed   = take con_arity as_RDRs
320             bs_needed   = take con_arity bs_RDRs
321             tys_needed  = dataConRawArgTys data_con
322
323             nested_compare_expr [ty] [a] [b]
324               = careful_compare_Case ty ltTag_Expr eqTag_Expr gtTag_Expr (HsVar a) (HsVar b)
325
326             nested_compare_expr (ty:tys) (a:as) (b:bs)
327               = let eq_expr = nested_compare_expr tys as bs
328                 in  careful_compare_Case ty ltTag_Expr eq_expr gtTag_Expr (HsVar a) (HsVar b)
329
330         default_rhs | null nullary_cons = impossible_Expr       -- Keep desugarer from complaining about
331                                                                 -- inexhaustive patterns
332                     | otherwise         = eqTag_Expr            -- Some nullary constructors;
333                                                                 -- Tags are equal, no args => return EQ
334     --------------------------------------------------------------------
335
336 defaulted = foldr1 AndMonoBinds [lt, le, ge, gt, max_, min_]
337
338 lt = mk_easy_FunMonoBind mkGeneratedSrcLoc lt_RDR [a_Pat, b_Pat] [] (
339             compare_Case true_Expr  false_Expr false_Expr a_Expr b_Expr)
340 le = mk_easy_FunMonoBind mkGeneratedSrcLoc le_RDR [a_Pat, b_Pat] [] (
341             compare_Case true_Expr  true_Expr  false_Expr a_Expr b_Expr)
342 ge = mk_easy_FunMonoBind mkGeneratedSrcLoc ge_RDR [a_Pat, b_Pat] [] (
343             compare_Case false_Expr true_Expr  true_Expr  a_Expr b_Expr)
344 gt = mk_easy_FunMonoBind mkGeneratedSrcLoc gt_RDR [a_Pat, b_Pat] [] (
345             compare_Case false_Expr false_Expr true_Expr  a_Expr b_Expr)
346
347 max_ = mk_easy_FunMonoBind mkGeneratedSrcLoc max_RDR [a_Pat, b_Pat] [] (
348             compare_Case b_Expr a_Expr a_Expr a_Expr b_Expr)
349 min_ = mk_easy_FunMonoBind mkGeneratedSrcLoc min_RDR [a_Pat, b_Pat] [] (
350             compare_Case a_Expr b_Expr b_Expr a_Expr b_Expr)
351 \end{code}
352
353 %************************************************************************
354 %*                                                                      *
355 \subsubsection{Generating @Enum@ instance declarations}
356 %*                                                                      *
357 %************************************************************************
358
359 @Enum@ can only be derived for enumeration types.  For a type
360 \begin{verbatim}
361 data Foo ... = N1 | N2 | ... | Nn
362 \end{verbatim}
363
364 we use both @con2tag_Foo@ and @tag2con_Foo@ functions, as well as a
365 @maxtag_Foo@ variable (all generated by @gen_tag_n_con_binds@).
366
367 \begin{verbatim}
368 instance ... Enum (Foo ...) where
369     toEnum i = tag2con_Foo i
370
371     enumFrom a = map tag2con_Foo [con2tag_Foo a .. maxtag_Foo]
372
373     -- or, really...
374     enumFrom a
375       = case con2tag_Foo a of
376           a# -> map tag2con_Foo (enumFromTo (I# a#) maxtag_Foo)
377
378    enumFromThen a b
379      = map tag2con_Foo [con2tag_Foo a, con2tag_Foo b .. maxtag_Foo]
380
381     -- or, really...
382     enumFromThen a b
383       = case con2tag_Foo a of { a# ->
384         case con2tag_Foo b of { b# ->
385         map tag2con_Foo (enumFromThenTo (I# a#) (I# b#) maxtag_Foo)
386         }}
387 \end{verbatim}
388
389 For @enumFromTo@ and @enumFromThenTo@, we use the default methods.
390
391 \begin{code}
392 gen_Enum_binds :: TyCon -> RdrNameMonoBinds
393
394 gen_Enum_binds tycon
395   = to_enum             `AndMonoBinds`
396     enum_from           `AndMonoBinds`
397     enum_from_then      `AndMonoBinds`
398     from_enum
399   where
400     tycon_loc = getSrcLoc tycon
401
402     to_enum
403       = mk_easy_FunMonoBind tycon_loc toEnum_RDR [a_Pat] [] $
404         mk_easy_App (tag2con_RDR tycon) [a_RDR]
405
406     enum_from
407       = mk_easy_FunMonoBind tycon_loc enumFrom_RDR [a_Pat] [] $
408           untag_Expr tycon [(a_RDR, ah_RDR)] $
409           HsApp (mk_easy_App map_RDR [tag2con_RDR tycon]) $
410             HsPar (enum_from_to_Expr
411                     (mk_easy_App mkInt_RDR [ah_RDR])
412                     (HsVar (maxtag_RDR tycon)))
413
414     enum_from_then
415       = mk_easy_FunMonoBind tycon_loc enumFromThen_RDR [a_Pat, b_Pat] [] $
416           untag_Expr tycon [(a_RDR, ah_RDR), (b_RDR, bh_RDR)] $
417           HsApp (mk_easy_App map_RDR [tag2con_RDR tycon]) $
418             HsPar (enum_from_then_to_Expr
419                     (mk_easy_App mkInt_RDR [ah_RDR])
420                     (mk_easy_App mkInt_RDR [bh_RDR])
421                     (HsVar (maxtag_RDR tycon)))
422
423     from_enum
424       = mk_easy_FunMonoBind tycon_loc fromEnum_RDR [a_Pat] [] $
425           untag_Expr tycon [(a_RDR, ah_RDR)] $
426           (mk_easy_App mkInt_RDR [ah_RDR])
427 \end{code}
428
429 %************************************************************************
430 %*                                                                      *
431 \subsubsection{Generating @Eval@ instance declarations}
432 %*                                                                      *
433 %************************************************************************
434
435 \begin{code}
436 gen_Eval_binds tycon = EmptyMonoBinds
437 \end{code}
438
439 %************************************************************************
440 %*                                                                      *
441 \subsubsection{Generating @Bounded@ instance declarations}
442 %*                                                                      *
443 %************************************************************************
444
445 \begin{code}
446 gen_Bounded_binds tycon
447   = if isEnumerationTyCon tycon then
448         min_bound_enum `AndMonoBinds` max_bound_enum
449     else
450         ASSERT(length data_cons == 1)
451         min_bound_1con `AndMonoBinds` max_bound_1con
452   where
453     data_cons = tyConDataCons tycon
454     tycon_loc = getSrcLoc tycon
455
456     ----- enum-flavored: ---------------------------
457     min_bound_enum = mk_easy_FunMonoBind tycon_loc minBound_RDR [] [] (HsVar data_con_1_RDR)
458     max_bound_enum = mk_easy_FunMonoBind tycon_loc maxBound_RDR [] [] (HsVar data_con_N_RDR)
459
460     data_con_1    = head data_cons
461     data_con_N    = last data_cons
462     data_con_1_RDR = qual_orig_name data_con_1
463     data_con_N_RDR = qual_orig_name data_con_N
464
465     ----- single-constructor-flavored: -------------
466     arity          = dataConNumFields data_con_1
467
468     min_bound_1con = mk_easy_FunMonoBind tycon_loc minBound_RDR [] [] $
469                      mk_easy_App data_con_1_RDR (nOfThem arity minBound_RDR)
470     max_bound_1con = mk_easy_FunMonoBind tycon_loc maxBound_RDR [] [] $
471                      mk_easy_App data_con_1_RDR (nOfThem arity maxBound_RDR)
472 \end{code}
473
474 %************************************************************************
475 %*                                                                      *
476 \subsubsection{Generating @Ix@ instance declarations}
477 %*                                                                      *
478 %************************************************************************
479
480 Deriving @Ix@ is only possible for enumeration types and
481 single-constructor types.  We deal with them in turn.
482
483 For an enumeration type, e.g.,
484 \begin{verbatim}
485     data Foo ... = N1 | N2 | ... | Nn
486 \end{verbatim}
487 things go not too differently from @Enum@:
488 \begin{verbatim}
489 instance ... Ix (Foo ...) where
490     range (a, b)
491       = map tag2con_Foo [con2tag_Foo a .. con2tag_Foo b]
492
493     -- or, really...
494     range (a, b)
495       = case (con2tag_Foo a) of { a# ->
496         case (con2tag_Foo b) of { b# ->
497         map tag2con_Foo (enumFromTo (I# a#) (I# b#))
498         }}
499
500     index c@(a, b) d
501       = if inRange c d
502         then case (con2tag_Foo d -# con2tag_Foo a) of
503                r# -> I# r#
504         else error "Ix.Foo.index: out of range"
505
506     inRange (a, b) c
507       = let
508             p_tag = con2tag_Foo c
509         in
510         p_tag >= con2tag_Foo a && p_tag <= con2tag_Foo b
511
512     -- or, really...
513     inRange (a, b) c
514       = case (con2tag_Foo a)   of { a_tag ->
515         case (con2tag_Foo b)   of { b_tag ->
516         case (con2tag_Foo c)   of { c_tag ->
517         if (c_tag >=# a_tag) then
518           c_tag <=# b_tag
519         else
520           False
521         }}}
522 \end{verbatim}
523 (modulo suitable case-ification to handle the unboxed tags)
524
525 For a single-constructor type (NB: this includes all tuples), e.g.,
526 \begin{verbatim}
527     data Foo ... = MkFoo a b Int Double c c
528 \end{verbatim}
529 we follow the scheme given in Figure~19 of the Haskell~1.2 report
530 (p.~147).
531
532 \begin{code}
533 gen_Ix_binds :: TyCon -> RdrNameMonoBinds
534
535 gen_Ix_binds tycon
536   = if isEnumerationTyCon tycon
537     then enum_ixes
538     else single_con_ixes
539   where
540     tycon_str = getOccString tycon
541     tycon_loc = getSrcLoc tycon
542
543     --------------------------------------------------------------
544     enum_ixes = enum_range `AndMonoBinds`
545                 enum_index `AndMonoBinds` enum_inRange
546
547     enum_range
548       = mk_easy_FunMonoBind tycon_loc range_RDR [TuplePatIn [a_Pat, b_Pat]] [] $
549           untag_Expr tycon [(a_RDR, ah_RDR)] $
550           untag_Expr tycon [(b_RDR, bh_RDR)] $
551           HsApp (mk_easy_App map_RDR [tag2con_RDR tycon]) $
552               HsPar (enum_from_to_Expr
553                         (mk_easy_App mkInt_RDR [ah_RDR])
554                         (mk_easy_App mkInt_RDR [bh_RDR]))
555
556     enum_index
557       = mk_easy_FunMonoBind tycon_loc index_RDR [AsPatIn c_RDR (TuplePatIn [a_Pat, b_Pat]), d_Pat] [] (
558         HsIf (HsPar (mk_easy_App inRange_RDR [c_RDR, d_RDR])) (
559            untag_Expr tycon [(a_RDR, ah_RDR)] (
560            untag_Expr tycon [(d_RDR, dh_RDR)] (
561            let
562                 grhs = [OtherwiseGRHS (mk_easy_App mkInt_RDR [c_RDR]) tycon_loc]
563            in
564            HsCase
565              (genOpApp (HsVar dh_RDR) minusH_RDR (HsVar ah_RDR))
566              [PatMatch (VarPatIn c_RDR)
567                                 (GRHSMatch (GRHSsAndBindsIn grhs EmptyBinds))]
568              tycon_loc
569            ))
570         ) {-else-} (
571            HsApp (HsVar error_RDR) (HsLit (HsString (_PK_ ("Ix."++tycon_str++".index: out of range\n"))))
572         )
573         tycon_loc)
574
575     enum_inRange
576       = mk_easy_FunMonoBind tycon_loc inRange_RDR [TuplePatIn [a_Pat, b_Pat], c_Pat] [] (
577           untag_Expr tycon [(a_RDR, ah_RDR)] (
578           untag_Expr tycon [(b_RDR, bh_RDR)] (
579           untag_Expr tycon [(c_RDR, ch_RDR)] (
580           HsIf (genOpApp (HsVar ch_RDR) geH_RDR (HsVar ah_RDR)) (
581              (genOpApp (HsVar ch_RDR) leH_RDR (HsVar bh_RDR))
582           ) {-else-} (
583              false_Expr
584           ) tycon_loc))))
585
586     --------------------------------------------------------------
587     single_con_ixes = single_con_range `AndMonoBinds`
588                 single_con_index `AndMonoBinds` single_con_inRange
589
590     data_con
591       = case maybeTyConSingleCon tycon of -- just checking...
592           Nothing -> panic "get_Ix_binds"
593           Just dc -> if (any isPrimType (dataConRawArgTys dc)) then
594                          error ("ERROR: Can't derive Ix for a single-constructor type with primitive argument types: "++tycon_str)
595                      else
596                          dc
597
598     con_arity   = dataConNumFields data_con
599     data_con_RDR = qual_orig_name data_con
600     con_pat  xs = ConPatIn data_con_RDR (map VarPatIn xs)
601     con_expr xs = mk_easy_App data_con_RDR xs
602
603     as_needed = take con_arity as_RDRs
604     bs_needed = take con_arity bs_RDRs
605     cs_needed = take con_arity cs_RDRs
606
607     --------------------------------------------------------------
608     single_con_range
609       = mk_easy_FunMonoBind tycon_loc range_RDR [TuplePatIn [con_pat as_needed, con_pat bs_needed]] [] $
610         HsDo ListComp stmts tycon_loc
611       where
612         stmts = zipWith3Equal "single_con_range" mk_qual as_needed bs_needed cs_needed
613                 ++
614                 [ReturnStmt (con_expr cs_needed)]
615
616         mk_qual a b c = BindStmt (VarPatIn c)
617                                  (HsApp (HsVar range_RDR) (ExplicitTuple [HsVar a, HsVar b]))
618                                  tycon_loc
619
620     ----------------
621     single_con_index
622       = mk_easy_FunMonoBind tycon_loc index_RDR [TuplePatIn [con_pat as_needed, con_pat bs_needed], con_pat cs_needed] [range_size] (
623         foldl mk_index (HsLit (HsInt 0)) (zip3 as_needed bs_needed cs_needed))
624       where
625         mk_index multiply_by (l, u, i)
626           = genOpApp (
627                 (HsApp (HsApp (HsVar index_RDR) (ExplicitTuple [HsVar l, HsVar u])) (HsVar i))
628            ) plus_RDR (
629                 genOpApp (
630                     (HsApp (HsVar rangeSize_RDR) (ExplicitTuple [HsVar l, HsVar u]))
631                 ) times_RDR multiply_by
632            )
633
634         range_size
635           = mk_easy_FunMonoBind tycon_loc rangeSize_RDR [TuplePatIn [a_Pat, b_Pat]] [] (
636                 genOpApp (
637                     (HsApp (HsApp (HsVar index_RDR) (ExplicitTuple [a_Expr, b_Expr])) b_Expr)
638                 ) plus_RDR (HsLit (HsInt 1)))
639
640     ------------------
641     single_con_inRange
642       = mk_easy_FunMonoBind tycon_loc inRange_RDR 
643                            [TuplePatIn [con_pat as_needed, con_pat bs_needed], con_pat cs_needed]
644                            [] (
645           foldl1 and_Expr (zipWith3Equal "single_con_inRange" in_range as_needed bs_needed cs_needed))
646       where
647         in_range a b c = HsApp (HsApp (HsVar inRange_RDR) (ExplicitTuple [HsVar a, HsVar b])) (HsVar c)
648 \end{code}
649
650 %************************************************************************
651 %*                                                                      *
652 \subsubsection{Generating @Read@ instance declarations}
653 %*                                                                      *
654 %************************************************************************
655
656 Ignoring all the infix-ery mumbo jumbo (ToDo)
657
658 \begin{code}
659 gen_Read_binds :: TyCon -> RdrNameMonoBinds
660
661 gen_Read_binds tycon
662   = reads_prec `AndMonoBinds` read_list
663   where
664     tycon_loc = getSrcLoc tycon
665     -----------------------------------------------------------------------
666     read_list = mk_easy_FunMonoBind tycon_loc readList_RDR [] []
667                   (HsApp (HsVar readList___RDR) (HsPar (HsApp (HsVar readsPrec_RDR) (HsLit (HsInt 0)))))
668     -----------------------------------------------------------------------
669     reads_prec
670       = let
671             read_con_comprehensions
672               = map read_con (tyConDataCons tycon)
673         in
674         mk_easy_FunMonoBind tycon_loc readsPrec_RDR [a_Pat, b_Pat] [] (
675               foldr1 append_Expr read_con_comprehensions
676         )
677       where
678         read_con data_con   -- note: "b" is the string being "read"
679           = let
680                 data_con_RDR = qual_orig_name data_con
681                 data_con_str= occNameString (getOccName data_con)
682                 con_arity   = dataConNumFields data_con
683                 as_needed   = take con_arity as_RDRs
684                 bs_needed   = take con_arity bs_RDRs
685                 con_expr    = mk_easy_App data_con_RDR as_needed
686                 nullary_con = isNullaryDataCon data_con
687
688                 con_qual
689                   = BindStmt
690                       (TuplePatIn [LitPatIn (HsString data_con_str), d_Pat])
691                       (HsApp (HsVar lex_RDR) c_Expr)
692                       tycon_loc
693
694                 field_quals = snd (mapAccumL mk_qual d_Expr (zipEqual "as_needed" as_needed bs_needed))
695                 mk_qual draw_from (con_field, str_left)
696                   = (HsVar str_left,    -- what to draw from down the line...
697                          BindStmt
698                           (TuplePatIn [VarPatIn con_field, VarPatIn str_left])
699                           (HsApp (HsApp (HsVar readsPrec_RDR) (HsLit (HsInt 10))) draw_from)
700                           tycon_loc
701                     )
702
703                 result_expr = ExplicitTuple [con_expr, if null bs_needed 
704                                                        then d_Expr 
705                                                        else HsVar (last bs_needed)]
706
707                 stmts = (con_qual : field_quals) ++ [ReturnStmt result_expr]
708                 
709
710                 read_paren_arg
711                   = if nullary_con then -- must be False (parens are surely optional)
712                        false_Expr
713                     else -- parens depend on precedence...
714                        HsPar (genOpApp a_Expr gt_RDR (HsLit (HsInt 9)))
715             in
716             HsApp (
717               readParen_Expr read_paren_arg $ HsPar $
718                  HsLam (mk_easy_Match tycon_loc [c_Pat] [] $
719                         HsDo ListComp stmts tycon_loc)
720               ) (HsVar b_RDR)
721 \end{code}
722
723 %************************************************************************
724 %*                                                                      *
725 \subsubsection{Generating @Show@ instance declarations}
726 %*                                                                      *
727 %************************************************************************
728
729 Ignoring all the infix-ery mumbo jumbo (ToDo)
730
731 \begin{code}
732 gen_Show_binds :: TyCon -> RdrNameMonoBinds
733
734 gen_Show_binds tycon
735   = shows_prec `AndMonoBinds` show_list
736   where
737     tycon_loc = getSrcLoc tycon
738     -----------------------------------------------------------------------
739     show_list = mk_easy_FunMonoBind tycon_loc showList_RDR [] []
740                   (HsApp (HsVar showList___RDR) (HsPar (HsApp (HsVar showsPrec_RDR) (HsLit (HsInt 0)))))
741     -----------------------------------------------------------------------
742     shows_prec
743       = mk_FunMonoBind tycon_loc showsPrec_RDR (map pats_etc (tyConDataCons tycon))
744       where
745         pats_etc data_con
746           = let
747                 data_con_RDR = qual_orig_name data_con
748                 con_arity   = dataConNumFields data_con
749                 bs_needed   = take con_arity bs_RDRs
750                 con_pat     = ConPatIn data_con_RDR (map VarPatIn bs_needed)
751                 nullary_con = isNullaryDataCon data_con
752
753                 show_con
754                   = let nm = occNameString (getOccName data_con)
755                         space_maybe = if nullary_con then _NIL_ else SLIT(" ")
756                     in
757                         HsApp (HsVar showString_RDR) (HsLit (HsString (nm _APPEND_ space_maybe)))
758
759                 show_thingies = show_con : (spacified real_show_thingies)
760
761                 real_show_thingies
762                   = [ HsApp (HsApp (HsVar showsPrec_RDR) (HsLit (HsInt 10))) (HsVar b)
763                   | b <- bs_needed ]
764             in
765             if nullary_con then  -- skip the showParen junk...
766                 ASSERT(null bs_needed)
767                 ([a_Pat, con_pat], show_con)
768             else
769                 ([a_Pat, con_pat],
770                     showParen_Expr (HsPar (genOpApp a_Expr ge_RDR (HsLit (HsInt 10))))
771                                    (HsPar (nested_compose_Expr show_thingies)))
772           where
773             spacified []     = []
774             spacified [x]    = [x]
775             spacified (x:xs) = (x : (HsVar showSpace_RDR) : spacified xs)
776 \end{code}
777
778 %************************************************************************
779 %*                                                                      *
780 \subsection{Generating extra binds (@con2tag@ and @tag2con@)}
781 %*                                                                      *
782 %************************************************************************
783
784 \begin{verbatim}
785 data Foo ... = ...
786
787 con2tag_Foo :: Foo ... -> Int#
788 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
789 maxtag_Foo  :: Int              -- ditto (NB: not unboxed)
790 \end{verbatim}
791
792 The `tags' here start at zero, hence the @fIRST_TAG@ (currently one)
793 fiddling around.
794
795 \begin{code}
796 data TagThingWanted
797   = GenCon2Tag | GenTag2Con | GenMaxTag
798
799 gen_tag_n_con_monobind
800     :: (RdrName,            -- (proto)Name for the thing in question
801         TyCon,              -- tycon in question
802         TagThingWanted)
803     -> RdrNameMonoBinds
804
805 gen_tag_n_con_monobind (rdr_name, tycon, GenCon2Tag)
806   = mk_FunMonoBind (getSrcLoc tycon) rdr_name (map mk_stuff (tyConDataCons tycon))
807   where
808     mk_stuff :: DataCon -> ([RdrNamePat], RdrNameHsExpr)
809
810     mk_stuff var
811       = ASSERT(isDataCon var)
812         ([pat], HsLit (HsIntPrim (toInteger ((dataConTag var) - fIRST_TAG))))
813       where
814         pat    = ConPatIn var_RDR (nOfThem (dataConNumFields var) WildPatIn)
815         var_RDR = qual_orig_name var
816
817 gen_tag_n_con_monobind (rdr_name, tycon, GenTag2Con)
818   = mk_FunMonoBind (getSrcLoc tycon) rdr_name (map mk_stuff (tyConDataCons tycon) ++ 
819                                                              [([WildPatIn], impossible_Expr)])
820   where
821     mk_stuff :: DataCon -> ([RdrNamePat], RdrNameHsExpr)
822
823     mk_stuff var
824       = ASSERT(isDataCon var)
825         ([lit_pat], HsVar var_RDR)
826       where
827         lit_pat = ConPatIn mkInt_RDR [LitPatIn (HsIntPrim (toInteger ((dataConTag var) - fIRST_TAG)))]
828         var_RDR  = qual_orig_name var
829
830 gen_tag_n_con_monobind (rdr_name, tycon, GenMaxTag)
831   = mk_easy_FunMonoBind (getSrcLoc tycon) 
832                 rdr_name [] [] (HsApp (HsVar mkInt_RDR) (HsLit (HsIntPrim max_tag)))
833   where
834     max_tag =  case (tyConDataCons tycon) of
835                  data_cons -> toInteger ((length data_cons) - fIRST_TAG)
836
837 \end{code}
838
839 %************************************************************************
840 %*                                                                      *
841 \subsection{Utility bits for generating bindings}
842 %*                                                                      *
843 %************************************************************************
844
845 @mk_easy_FunMonoBind fun pats binds expr@ generates:
846 \begin{verbatim}
847     fun pat1 pat2 ... patN = expr where binds
848 \end{verbatim}
849
850 @mk_FunMonoBind fun [([p1a, p1b, ...], e1), ...]@ is for
851 multi-clause definitions; it generates:
852 \begin{verbatim}
853     fun p1a p1b ... p1N = e1
854     fun p2a p2b ... p2N = e2
855     ...
856     fun pMa pMb ... pMN = eM
857 \end{verbatim}
858
859 \begin{code}
860 mk_easy_FunMonoBind :: SrcLoc -> RdrName -> [RdrNamePat]
861                     -> [RdrNameMonoBinds] -> RdrNameHsExpr
862                     -> RdrNameMonoBinds
863
864 mk_easy_FunMonoBind loc fun pats binds expr
865   = FunMonoBind fun False{-not infix-} [mk_easy_Match loc pats binds expr] loc
866
867 mk_easy_Match loc pats binds expr
868   = mk_match loc pats expr (mkbind binds)
869   where
870     mkbind [] = EmptyBinds
871     mkbind bs = SingleBind (RecBind (foldr1 AndMonoBinds bs))
872         -- The renamer expects everything in its input to be a
873         -- "recursive" MonoBinds, and it is its job to sort things out
874         -- from there.
875
876 mk_FunMonoBind  :: SrcLoc -> RdrName
877                 -> [([RdrNamePat], RdrNameHsExpr)]
878                 -> RdrNameMonoBinds
879
880 mk_FunMonoBind loc fun [] = panic "TcGenDeriv:mk_FunMonoBind"
881 mk_FunMonoBind loc fun pats_and_exprs
882   = FunMonoBind fun False{-not infix-}
883                 [ mk_match loc p e EmptyBinds | (p,e) <-pats_and_exprs ]
884                 loc
885
886 mk_match loc pats expr binds
887   = foldr PatMatch
888           (GRHSMatch (GRHSsAndBindsIn [OtherwiseGRHS expr loc] binds))
889           (map paren pats)
890   where
891     paren p@(VarPatIn _) = p
892     paren other_p        = ParPatIn other_p
893 \end{code}
894
895 \begin{code}
896 mk_easy_App f xs = foldl HsApp (HsVar f) (map HsVar xs)
897 \end{code}
898
899 ToDo: Better SrcLocs.
900
901 \begin{code}
902 compare_Case, cmp_eq_Expr ::
903           RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
904           -> RdrNameHsExpr -> RdrNameHsExpr
905           -> RdrNameHsExpr
906 compare_gen_Case ::
907           RdrName
908           -> RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
909           -> RdrNameHsExpr -> RdrNameHsExpr
910           -> RdrNameHsExpr
911 careful_compare_Case :: -- checks for primitive types...
912           Type
913           -> RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
914           -> RdrNameHsExpr -> RdrNameHsExpr
915           -> RdrNameHsExpr
916
917 compare_Case = compare_gen_Case compare_RDR
918 cmp_eq_Expr = compare_gen_Case cmp_eq_RDR
919
920 compare_gen_Case fun lt eq gt a b
921   = HsCase (HsPar (HsApp (HsApp (HsVar fun) a) b)) {-of-}
922       [PatMatch (ConPatIn ltTag_RDR [])
923           (GRHSMatch (GRHSsAndBindsIn [OtherwiseGRHS lt mkGeneratedSrcLoc] EmptyBinds)),
924
925        PatMatch (ConPatIn eqTag_RDR [])
926           (GRHSMatch (GRHSsAndBindsIn [OtherwiseGRHS eq mkGeneratedSrcLoc] EmptyBinds)),
927
928        PatMatch (ConPatIn gtTag_RDR [])
929           (GRHSMatch (GRHSsAndBindsIn [OtherwiseGRHS gt mkGeneratedSrcLoc] EmptyBinds))]
930        mkGeneratedSrcLoc
931
932 careful_compare_Case ty lt eq gt a b
933   = if not (isPrimType ty) then
934        compare_gen_Case compare_RDR lt eq gt a b
935
936     else -- we have to do something special for primitive things...
937        HsIf (genOpApp a relevant_eq_op b)
938             eq
939             (HsIf (genOpApp a relevant_lt_op b) lt gt mkGeneratedSrcLoc)
940             mkGeneratedSrcLoc
941   where
942     relevant_eq_op = assoc_ty_id eq_op_tbl ty
943     relevant_lt_op = assoc_ty_id lt_op_tbl ty
944
945 assoc_ty_id tyids ty 
946   = if null res then panic "assoc_ty"
947     else head res
948   where
949     res = [id | (ty',id) <- tyids, eqTy ty ty']
950
951 eq_op_tbl =
952     [(charPrimTy,       eqH_Char_RDR)
953     ,(intPrimTy,        eqH_Int_RDR)
954     ,(wordPrimTy,       eqH_Word_RDR)
955     ,(addrPrimTy,       eqH_Addr_RDR)
956     ,(floatPrimTy,      eqH_Float_RDR)
957     ,(doublePrimTy,     eqH_Double_RDR)
958     ]
959
960 lt_op_tbl =
961     [(charPrimTy,       ltH_Char_RDR)
962     ,(intPrimTy,        ltH_Int_RDR)
963     ,(wordPrimTy,       ltH_Word_RDR)
964     ,(addrPrimTy,       ltH_Addr_RDR)
965     ,(floatPrimTy,      ltH_Float_RDR)
966     ,(doublePrimTy,     ltH_Double_RDR)
967     ]
968
969 -----------------------------------------------------------------------
970
971 and_Expr, append_Expr :: RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
972
973 and_Expr    a b = genOpApp a and_RDR    b
974 append_Expr a b = genOpApp a append_RDR b
975
976 -----------------------------------------------------------------------
977
978 eq_Expr :: Type -> RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
979 eq_Expr ty a b
980   = if not (isPrimType ty) then
981        genOpApp a eq_RDR  b
982     else -- we have to do something special for primitive things...
983        genOpApp a relevant_eq_op b
984   where
985     relevant_eq_op = assoc_ty_id eq_op_tbl ty
986 \end{code}
987
988 \begin{code}
989 untag_Expr :: TyCon -> [(RdrName, RdrName)] -> RdrNameHsExpr -> RdrNameHsExpr
990 untag_Expr tycon [] expr = expr
991 untag_Expr tycon ((untag_this, put_tag_here) : more) expr
992   = HsCase (HsPar (HsApp (con2tag_Expr tycon) (HsVar untag_this))) {-of-}
993       [PatMatch (VarPatIn put_tag_here)
994                         (GRHSMatch (GRHSsAndBindsIn grhs EmptyBinds))]
995       mkGeneratedSrcLoc
996   where
997     grhs = [OtherwiseGRHS (untag_Expr tycon more expr) mkGeneratedSrcLoc]
998
999 cmp_tags_Expr :: RdrName                -- Comparison op
1000              -> RdrName -> RdrName      -- Things to compare
1001              -> RdrNameHsExpr           -- What to return if true
1002              -> RdrNameHsExpr           -- What to return if false
1003              -> RdrNameHsExpr
1004
1005 cmp_tags_Expr op a b true_case false_case
1006   = HsIf (genOpApp (HsVar a) op (HsVar b)) true_case false_case mkGeneratedSrcLoc
1007
1008 enum_from_to_Expr
1009         :: RdrNameHsExpr -> RdrNameHsExpr
1010         -> RdrNameHsExpr
1011 enum_from_then_to_Expr
1012         :: RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
1013         -> RdrNameHsExpr
1014
1015 enum_from_to_Expr      f   t2 = HsApp (HsApp (HsVar enumFromTo_RDR) f) t2
1016 enum_from_then_to_Expr f t t2 = HsApp (HsApp (HsApp (HsVar enumFromThenTo_RDR) f) t) t2
1017
1018 showParen_Expr, readParen_Expr
1019         :: RdrNameHsExpr -> RdrNameHsExpr
1020         -> RdrNameHsExpr
1021
1022 showParen_Expr e1 e2 = HsApp (HsApp (HsVar showParen_RDR) e1) e2
1023 readParen_Expr e1 e2 = HsApp (HsApp (HsVar readParen_RDR) e1) e2
1024
1025 nested_compose_Expr :: [RdrNameHsExpr] -> RdrNameHsExpr
1026
1027 nested_compose_Expr [e] = parenify e
1028 nested_compose_Expr (e:es)
1029   = HsApp (HsApp (HsVar compose_RDR) (parenify e)) (nested_compose_Expr es)
1030
1031 -- impossible_Expr is used in case RHSs that should never happen.
1032 -- We generate these to keep the desugarer from complaining that they *might* happen!
1033 impossible_Expr = HsApp (HsVar error_RDR) (HsLit (HsString (_PK_ "Urk! in TcGenDeriv")))
1034
1035 parenify e@(HsVar _) = e
1036 parenify e           = HsPar e
1037
1038 -- genOpApp wraps brackets round the operator application, so that the
1039 -- renamer won't subsequently try to re-associate it. 
1040 -- For some reason the renamer doesn't reassociate it right, and I can't
1041 -- be bothered to find out why just now.
1042
1043 genOpApp e1 op e2 = mkOpApp e1 op e2
1044 \end{code}
1045
1046 \begin{code}
1047 qual_orig_name n = case modAndOcc n of { (m,n) -> Qual m n }
1048
1049 a_RDR           = varUnqual SLIT("a")
1050 b_RDR           = varUnqual SLIT("b")
1051 c_RDR           = varUnqual SLIT("c")
1052 d_RDR           = varUnqual SLIT("d")
1053 ah_RDR          = varUnqual SLIT("a#")
1054 bh_RDR          = varUnqual SLIT("b#")
1055 ch_RDR          = varUnqual SLIT("c#")
1056 dh_RDR          = varUnqual SLIT("d#")
1057 cmp_eq_RDR      = varUnqual SLIT("cmp_eq")
1058 rangeSize_RDR   = varUnqual SLIT("rangeSize")
1059
1060 as_RDRs         = [ varUnqual (_PK_ ("a"++show i)) | i <- [(1::Int) .. ] ]
1061 bs_RDRs         = [ varUnqual (_PK_ ("b"++show i)) | i <- [(1::Int) .. ] ]
1062 cs_RDRs         = [ varUnqual (_PK_ ("c"++show i)) | i <- [(1::Int) .. ] ]
1063
1064 a_Expr          = HsVar a_RDR
1065 b_Expr          = HsVar b_RDR
1066 c_Expr          = HsVar c_RDR
1067 d_Expr          = HsVar d_RDR
1068 ltTag_Expr      = HsVar ltTag_RDR
1069 eqTag_Expr      = HsVar eqTag_RDR
1070 gtTag_Expr      = HsVar gtTag_RDR
1071 false_Expr      = HsVar false_RDR
1072 true_Expr       = HsVar true_RDR
1073
1074 con2tag_Expr tycon = HsVar (con2tag_RDR tycon)
1075
1076 a_Pat           = VarPatIn a_RDR
1077 b_Pat           = VarPatIn b_RDR
1078 c_Pat           = VarPatIn c_RDR
1079 d_Pat           = VarPatIn d_RDR
1080
1081 con2tag_RDR, tag2con_RDR, maxtag_RDR :: TyCon -> RdrName
1082
1083 con2tag_RDR tycon = varUnqual (SLIT("con2tag_") _APPEND_ occNameString (getOccName tycon) _APPEND_ SLIT("#"))
1084 tag2con_RDR tycon = varUnqual (SLIT("tag2con_") _APPEND_ occNameString (getOccName tycon) _APPEND_ SLIT("#"))
1085 maxtag_RDR tycon  = varUnqual (SLIT("maxtag_")  _APPEND_ occNameString (getOccName tycon) _APPEND_ SLIT("#"))
1086 \end{code}