ac77456654155076d8feffc6f70ccb57da85c14c
[ghc-hetmet.git] / ghc / compiler / typecheck / TcGenDeriv.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
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 module TcGenDeriv (
13         gen_Bounded_binds,
14         gen_Enum_binds,
15         gen_Eq_binds,
16         gen_Ix_binds,
17         gen_Ord_binds,
18         gen_Read_binds,
19         gen_Show_binds,
20         gen_tag_n_con_monobind,
21
22         con2tag_RDR, tag2con_RDR, maxtag_RDR,
23
24         TagThingWanted(..)
25     ) where
26
27 #include "HsVersions.h"
28
29 import HsSyn            ( InPat(..), HsExpr(..), MonoBinds(..),
30                           Match(..), GRHSs(..), Stmt(..), HsLit(..),
31                           HsBinds(..), HsType(..), HsDoContext(..),
32                           unguardedRHS, mkSimpleMatch, mkMonoBind, andMonoBindList, placeHolderType
33                         )
34 import RdrHsSyn         ( mkHsOpApp, RdrNameMonoBinds, RdrNameHsExpr, RdrNamePat )
35 import RdrName          ( RdrName, mkUnqual )
36 import BasicTypes       ( RecFlag(..), Fixity(..), FixityDirection(..)
37                         , maxPrecedence
38                         , Boxity(..)
39                         )
40 import FieldLabel       ( fieldLabelName )
41 import DataCon          ( isNullaryDataCon, dataConTag,
42                           dataConOrigArgTys, dataConSourceArity, fIRST_TAG,
43                           DataCon, 
44                           dataConFieldLabels )
45 import Name             ( getOccString, getOccName, getSrcLoc, occNameString, 
46                           occNameUserString, nameRdrName, varName,
47                           Name, NamedThing(..), 
48                           isDataSymOcc, isSymOcc
49                         )
50
51 import HscTypes         ( FixityEnv, lookupFixity )
52 import PrelInfo         -- Lots of RdrNames
53 import SrcLoc           ( generatedSrcLoc, SrcLoc )
54 import TyCon            ( TyCon, isNewTyCon, tyConDataCons, isEnumerationTyCon,
55                           maybeTyConSingleCon, tyConFamilySize
56                         )
57 import TcType           ( isUnLiftedType, tcEqType, Type )
58 import TysPrim          ( charPrimTy, intPrimTy, wordPrimTy, addrPrimTy,
59                           floatPrimTy, doublePrimTy
60                         )
61 import Util             ( mapAccumL, zipEqual, zipWithEqual, isSingleton,
62                           zipWith3Equal, nOfThem )
63 import Panic            ( panic, assertPanic )
64 import Maybes           ( maybeToBool )
65 import Constants
66 import List             ( partition, intersperse )
67
68 #if __GLASGOW_HASKELL__ >= 404
69 import GlaExts          ( fromInt )
70 #endif
71 \end{code}
72
73 %************************************************************************
74 %*                                                                      *
75 \subsection{Generating code, by derivable class}
76 %*                                                                      *
77 %************************************************************************
78
79 %************************************************************************
80 %*                                                                      *
81 \subsubsection{Generating @Eq@ instance declarations}
82 %*                                                                      *
83 %************************************************************************
84
85 Here are the heuristics for the code we generate for @Eq@:
86 \begin{itemize}
87 \item
88   Let's assume we have a data type with some (possibly zero) nullary
89   data constructors and some ordinary, non-nullary ones (the rest,
90   also possibly zero of them).  Here's an example, with both \tr{N}ullary
91   and \tr{O}rdinary data cons.
92 \begin{verbatim}
93 data Foo ... = N1 | N2 ... | Nn | O1 a b | O2 Int | O3 Double b b | ...
94 \end{verbatim}
95
96 \item
97   For the ordinary constructors (if any), we emit clauses to do The
98   Usual Thing, e.g.,:
99
100 \begin{verbatim}
101 (==) (O1 a1 b1)    (O1 a2 b2)    = a1 == a2 && b1 == b2
102 (==) (O2 a1)       (O2 a2)       = a1 == a2
103 (==) (O3 a1 b1 c1) (O3 a2 b2 c2) = a1 == a2 && b1 == b2 && c1 == c2
104 \end{verbatim}
105
106   Note: if we're comparing unlifted things, e.g., if \tr{a1} and
107   \tr{a2} are \tr{Float#}s, then we have to generate
108 \begin{verbatim}
109 case (a1 `eqFloat#` a2) of
110   r -> r
111 \end{verbatim}
112   for that particular test.
113
114 \item
115   If there are any nullary constructors, we emit a catch-all clause of
116   the form:
117
118 \begin{verbatim}
119 (==) a b  = case (con2tag_Foo a) of { a# ->
120             case (con2tag_Foo b) of { b# ->
121             case (a# ==# b#)     of {
122               r -> r
123             }}}
124 \end{verbatim}
125
126   If there aren't any nullary constructors, we emit a simpler
127   catch-all:
128 \begin{verbatim}
129 (==) a b  = False
130 \end{verbatim}
131
132 \item
133   For the @(/=)@ method, we normally just use the default method.
134
135   If the type is an enumeration type, we could/may/should? generate
136   special code that calls @con2tag_Foo@, much like for @(==)@ shown
137   above.
138
139 \item
140   We thought about doing this: If we're also deriving @Ord@ for this
141   tycon, we generate:
142 \begin{verbatim}
143 instance ... Eq (Foo ...) where
144   (==) a b  = case (compare a b) of { _LT -> False; _EQ -> True ; _GT -> False}
145   (/=) a b  = case (compare a b) of { _LT -> True ; _EQ -> False; _GT -> True }
146 \begin{verbatim}
147   However, that requires that \tr{Ord <whatever>} was put in the context
148   for the instance decl, which it probably wasn't, so the decls
149   produced don't get through the typechecker.
150 \end{itemize}
151
152
153 deriveEq :: RdrName                             -- Class
154          -> RdrName                             -- Type constructor
155          -> [ (RdrName, [RdrType]) ]    -- Constructors
156          -> (RdrContext,                -- Context for the inst decl
157              [RdrBind],                 -- Binds in the inst decl
158              [RdrBind])                 -- Extra value bindings outside
159
160 deriveEq clas tycon constrs 
161   = (context, [eq_bind, ne_bind], [])
162   where
163     context = [(clas, [ty]) | (_, tys) <- constrs, ty <- tys]
164
165     ne_bind = mkBind 
166     (nullary_cons, non_nullary_cons) = partition is_nullary constrs
167     is_nullary (_, args) = null args
168
169 \begin{code}
170 gen_Eq_binds :: TyCon -> RdrNameMonoBinds
171
172 gen_Eq_binds tycon
173   = let
174         tycon_loc = getSrcLoc tycon
175         (nullary_cons, nonnullary_cons)
176            | isNewTyCon tycon = ([], tyConDataCons tycon)
177            | otherwise        = partition isNullaryDataCon (tyConDataCons tycon)
178
179         rest
180           = if (null nullary_cons) then
181                 case maybeTyConSingleCon tycon of
182                   Just _ -> []
183                   Nothing -> -- if cons don't match, then False
184                      [([wildPat, wildPat], false_Expr)]
185             else -- calc. and compare the tags
186                  [([a_Pat, b_Pat],
187                     untag_Expr tycon [(a_RDR,ah_RDR), (b_RDR,bh_RDR)]
188                                (genOpApp (HsVar ah_RDR) eqH_Int_RDR (HsVar bh_RDR)))]
189     in
190     mk_FunMonoBind tycon_loc eq_RDR ((map pats_etc nonnullary_cons) ++ rest)
191             `AndMonoBinds`
192     mk_easy_FunMonoBind tycon_loc ne_RDR [a_Pat, b_Pat] [] (
193         HsApp (HsVar not_RDR) (HsPar (mk_easy_App eq_RDR [a_RDR, b_RDR])))
194   where
195     ------------------------------------------------------------------
196     pats_etc data_con
197       = let
198             con1_pat = ConPatIn data_con_RDR (map VarPatIn as_needed)
199             con2_pat = ConPatIn data_con_RDR (map VarPatIn bs_needed)
200
201             data_con_RDR = qual_orig_name data_con
202             con_arity   = length tys_needed
203             as_needed   = take con_arity as_RDRs
204             bs_needed   = take con_arity bs_RDRs
205             tys_needed  = dataConOrigArgTys data_con
206         in
207         ([con1_pat, con2_pat], nested_eq_expr tys_needed as_needed bs_needed)
208       where
209         nested_eq_expr []  [] [] = true_Expr
210         nested_eq_expr tys as bs
211           = foldl1 and_Expr (zipWith3Equal "nested_eq" nested_eq tys as bs)
212           where
213             nested_eq ty a b = HsPar (eq_Expr ty (HsVar a) (HsVar b))
214 \end{code}
215
216 %************************************************************************
217 %*                                                                      *
218 \subsubsection{Generating @Ord@ instance declarations}
219 %*                                                                      *
220 %************************************************************************
221
222 For a derived @Ord@, we concentrate our attentions on @compare@
223 \begin{verbatim}
224 compare :: a -> a -> Ordering
225 data Ordering = LT | EQ | GT deriving ()
226 \end{verbatim}
227
228 We will use the same example data type as above:
229 \begin{verbatim}
230 data Foo ... = N1 | N2 ... | Nn | O1 a b | O2 Int | O3 Double b b | ...
231 \end{verbatim}
232
233 \begin{itemize}
234 \item
235   We do all the other @Ord@ methods with calls to @compare@:
236 \begin{verbatim}
237 instance ... (Ord <wurble> <wurble>) where
238     a <  b  = case (compare a b) of { LT -> True;  EQ -> False; GT -> False }
239     a <= b  = case (compare a b) of { LT -> True;  EQ -> True;  GT -> False }
240     a >= b  = case (compare a b) of { LT -> False; EQ -> True;  GT -> True  }
241     a >  b  = case (compare a b) of { LT -> False; EQ -> False; GT -> True  }
242
243     max a b = case (compare a b) of { LT -> b; EQ -> a;  GT -> a }
244     min a b = case (compare a b) of { LT -> a; EQ -> b;  GT -> b }
245
246     -- compare to come...
247 \end{verbatim}
248
249 \item
250   @compare@ always has two parts.  First, we use the compared
251   data-constructors' tags to deal with the case of different
252   constructors:
253 \begin{verbatim}
254 compare a b = case (con2tag_Foo a) of { a# ->
255               case (con2tag_Foo b) of { b# ->
256               case (a# ==# b#)     of {
257                True  -> cmp_eq a b
258                False -> case (a# <# b#) of
259                          True  -> _LT
260                          False -> _GT
261               }}}
262   where
263     cmp_eq = ... to come ...
264 \end{verbatim}
265
266 \item
267   We are only left with the ``help'' function @cmp_eq@, to deal with
268   comparing data constructors with the same tag.
269
270   For the ordinary constructors (if any), we emit the sorta-obvious
271   compare-style stuff; for our example:
272 \begin{verbatim}
273 cmp_eq (O1 a1 b1) (O1 a2 b2)
274   = case (compare a1 a2) of { LT -> LT; EQ -> compare b1 b2; GT -> GT }
275
276 cmp_eq (O2 a1) (O2 a2)
277   = compare a1 a2
278
279 cmp_eq (O3 a1 b1 c1) (O3 a2 b2 c2)
280   = case (compare a1 a2) of {
281       LT -> LT;
282       GT -> GT;
283       EQ -> case compare b1 b2 of {
284               LT -> LT;
285               GT -> GT;
286               EQ -> compare c1 c2
287             }
288     }
289 \end{verbatim}
290
291   Again, we must be careful about unlifted comparisons.  For example,
292   if \tr{a1} and \tr{a2} were \tr{Int#}s in the 2nd example above, we'd need to
293   generate:
294
295 \begin{verbatim}
296 cmp_eq lt eq gt (O2 a1) (O2 a2)
297   = compareInt# a1 a2
298   -- or maybe the unfolded equivalent
299 \end{verbatim}
300
301 \item
302   For the remaining nullary constructors, we already know that the
303   tags are equal so:
304 \begin{verbatim}
305 cmp_eq _ _ = EQ
306 \end{verbatim}
307 \end{itemize}
308
309 If there is only one constructor in the Data Type we don't need the WildCard Pattern. 
310 JJQC-30-Nov-1997
311
312 \begin{code}
313 gen_Ord_binds :: TyCon -> RdrNameMonoBinds
314
315 gen_Ord_binds tycon
316   = compare     -- `AndMonoBinds` compare       
317                 -- The default declaration in PrelBase handles this
318   where
319     tycon_loc = getSrcLoc tycon
320     --------------------------------------------------------------------
321     compare = mk_easy_FunMonoBind tycon_loc compare_RDR
322                 [a_Pat, b_Pat]
323                 [cmp_eq]
324             (if maybeToBool (maybeTyConSingleCon tycon) then
325
326 --              cmp_eq_Expr ltTag_Expr eqTag_Expr gtTag_Expr a_Expr b_Expr
327 -- Weird.  Was: case (cmp a b) of { LT -> LT; EQ -> EQ; GT -> GT }
328
329                 cmp_eq_Expr a_Expr b_Expr
330              else
331                 untag_Expr tycon [(a_RDR, ah_RDR), (b_RDR, bh_RDR)]
332                   (cmp_tags_Expr eqH_Int_RDR ah_RDR bh_RDR
333                         -- True case; they are equal
334                         -- If an enumeration type we are done; else
335                         -- recursively compare their components
336                     (if isEnumerationTyCon tycon then
337                         eqTag_Expr
338                      else
339 --                      cmp_eq_Expr ltTag_Expr eqTag_Expr gtTag_Expr a_Expr b_Expr
340 -- Ditto
341                         cmp_eq_Expr a_Expr b_Expr
342                     )
343                         -- False case; they aren't equal
344                         -- So we need to do a less-than comparison on the tags
345                     (cmp_tags_Expr ltH_Int_RDR ah_RDR bh_RDR ltTag_Expr gtTag_Expr)))
346
347     tycon_data_cons = tyConDataCons tycon
348     (nullary_cons, nonnullary_cons)
349        | isNewTyCon tycon = ([], tyConDataCons tycon)
350        | otherwise        = partition isNullaryDataCon tycon_data_cons
351
352     cmp_eq =
353        mk_FunMonoBind tycon_loc 
354                       cmp_eq_RDR 
355                       (if null nonnullary_cons && isSingleton nullary_cons then
356                            -- catch this specially to avoid warnings
357                            -- about overlapping patterns from the desugarer.
358                           let 
359                            data_con     = head nullary_cons
360                            data_con_RDR = qual_orig_name data_con
361                            pat          = ConPatIn data_con_RDR []
362                           in
363                           [([pat,pat], eqTag_Expr)]
364                        else
365                           map pats_etc nonnullary_cons ++
366                           -- leave out wildcards to silence desugarer.
367                           (if isSingleton tycon_data_cons then
368                               []
369                            else
370                               [([WildPatIn, WildPatIn], default_rhs)]))
371       where
372         pats_etc data_con
373           = ([con1_pat, con2_pat],
374              nested_compare_expr tys_needed as_needed bs_needed)
375           where
376             con1_pat = ConPatIn data_con_RDR (map VarPatIn as_needed)
377             con2_pat = ConPatIn data_con_RDR (map VarPatIn bs_needed)
378
379             data_con_RDR = qual_orig_name data_con
380             con_arity   = length tys_needed
381             as_needed   = take con_arity as_RDRs
382             bs_needed   = take con_arity bs_RDRs
383             tys_needed  = dataConOrigArgTys data_con
384
385             nested_compare_expr [ty] [a] [b]
386               = careful_compare_Case ty ltTag_Expr eqTag_Expr gtTag_Expr (HsVar a) (HsVar b)
387
388             nested_compare_expr (ty:tys) (a:as) (b:bs)
389               = let eq_expr = nested_compare_expr tys as bs
390                 in  careful_compare_Case ty ltTag_Expr eq_expr gtTag_Expr (HsVar a) (HsVar b)
391
392         default_rhs | null nullary_cons = impossible_Expr       -- Keep desugarer from complaining about
393                                                                 -- inexhaustive patterns
394                     | otherwise         = eqTag_Expr            -- Some nullary constructors;
395                                                                 -- Tags are equal, no args => return EQ
396 \end{code}
397
398 %************************************************************************
399 %*                                                                      *
400 \subsubsection{Generating @Enum@ instance declarations}
401 %*                                                                      *
402 %************************************************************************
403
404 @Enum@ can only be derived for enumeration types.  For a type
405 \begin{verbatim}
406 data Foo ... = N1 | N2 | ... | Nn
407 \end{verbatim}
408
409 we use both @con2tag_Foo@ and @tag2con_Foo@ functions, as well as a
410 @maxtag_Foo@ variable (all generated by @gen_tag_n_con_binds@).
411
412 \begin{verbatim}
413 instance ... Enum (Foo ...) where
414     succ x   = toEnum (1 + fromEnum x)
415     pred x   = toEnum (fromEnum x - 1)
416
417     toEnum i = tag2con_Foo i
418
419     enumFrom a = map tag2con_Foo [con2tag_Foo a .. maxtag_Foo]
420
421     -- or, really...
422     enumFrom a
423       = case con2tag_Foo a of
424           a# -> map tag2con_Foo (enumFromTo (I# a#) maxtag_Foo)
425
426    enumFromThen a b
427      = map tag2con_Foo [con2tag_Foo a, con2tag_Foo b .. maxtag_Foo]
428
429     -- or, really...
430     enumFromThen a b
431       = case con2tag_Foo a of { a# ->
432         case con2tag_Foo b of { b# ->
433         map tag2con_Foo (enumFromThenTo (I# a#) (I# b#) maxtag_Foo)
434         }}
435 \end{verbatim}
436
437 For @enumFromTo@ and @enumFromThenTo@, we use the default methods.
438
439 \begin{code}
440 gen_Enum_binds :: TyCon -> RdrNameMonoBinds
441
442 gen_Enum_binds tycon
443   = succ_enum           `AndMonoBinds`
444     pred_enum           `AndMonoBinds`
445     to_enum             `AndMonoBinds`
446     enum_from           `AndMonoBinds`
447     enum_from_then      `AndMonoBinds`
448     from_enum
449   where
450     tycon_loc = getSrcLoc tycon
451     occ_nm    = getOccString tycon
452
453     succ_enum
454       = mk_easy_FunMonoBind tycon_loc succ_RDR [a_Pat] [] $
455         untag_Expr tycon [(a_RDR, ah_RDR)] $
456         HsIf (HsApp (HsApp (HsVar eq_RDR) 
457                            (HsVar (maxtag_RDR tycon)))
458                            (mk_easy_App mkInt_RDR [ah_RDR]))
459              (illegal_Expr "succ" occ_nm "tried to take `succ' of last tag in enumeration")
460              (HsApp (HsVar (tag2con_RDR tycon))
461                     (HsApp (HsApp (HsVar plus_RDR)
462                                   (mk_easy_App mkInt_RDR [ah_RDR]))
463                            (HsLit (HsInt 1))))
464              tycon_loc
465                     
466     pred_enum
467       = mk_easy_FunMonoBind tycon_loc pred_RDR [a_Pat] [] $
468         untag_Expr tycon [(a_RDR, ah_RDR)] $
469         HsIf (HsApp (HsApp (HsVar eq_RDR) (HsLit (HsInt 0)))
470                     (mk_easy_App mkInt_RDR [ah_RDR]))
471              (illegal_Expr "pred" occ_nm "tried to take `pred' of first tag in enumeration")
472              (HsApp (HsVar (tag2con_RDR tycon))
473                            (HsApp (HsApp (HsVar plus_RDR)
474                                          (mk_easy_App mkInt_RDR [ah_RDR]))
475                                   (HsLit (HsInt (-1)))))
476              tycon_loc
477
478     to_enum
479       = mk_easy_FunMonoBind tycon_loc toEnum_RDR [a_Pat] [] $
480         HsIf (HsApp (HsApp 
481                     (HsVar and_RDR)
482                     (HsApp (HsApp (HsVar ge_RDR)
483                                   (HsVar a_RDR))
484                                   (HsLit (HsInt 0))))
485                     (HsApp (HsApp (HsVar le_RDR)
486                                   (HsVar a_RDR))
487                                   (HsVar (maxtag_RDR tycon))))
488              (mk_easy_App (tag2con_RDR tycon) [a_RDR])
489              (illegal_toEnum_tag occ_nm (maxtag_RDR tycon))
490              tycon_loc
491
492     enum_from
493       = mk_easy_FunMonoBind tycon_loc enumFrom_RDR [a_Pat] [] $
494           untag_Expr tycon [(a_RDR, ah_RDR)] $
495           HsApp (mk_easy_App map_RDR [tag2con_RDR tycon]) $
496             HsPar (enum_from_to_Expr
497                     (mk_easy_App mkInt_RDR [ah_RDR])
498                     (HsVar (maxtag_RDR tycon)))
499
500     enum_from_then
501       = mk_easy_FunMonoBind tycon_loc enumFromThen_RDR [a_Pat, b_Pat] [] $
502           untag_Expr tycon [(a_RDR, ah_RDR), (b_RDR, bh_RDR)] $
503           HsApp (mk_easy_App map_RDR [tag2con_RDR tycon]) $
504             HsPar (enum_from_then_to_Expr
505                     (mk_easy_App mkInt_RDR [ah_RDR])
506                     (mk_easy_App mkInt_RDR [bh_RDR])
507                     (HsIf  (HsApp (HsApp (HsVar gt_RDR)
508                                          (mk_easy_App mkInt_RDR [ah_RDR]))
509                                          (mk_easy_App mkInt_RDR [bh_RDR]))
510                            (HsLit (HsInt 0))
511                            (HsVar (maxtag_RDR tycon))
512                            tycon_loc))
513
514     from_enum
515       = mk_easy_FunMonoBind tycon_loc fromEnum_RDR [a_Pat] [] $
516           untag_Expr tycon [(a_RDR, ah_RDR)] $
517           (mk_easy_App mkInt_RDR [ah_RDR])
518 \end{code}
519
520 %************************************************************************
521 %*                                                                      *
522 \subsubsection{Generating @Bounded@ instance declarations}
523 %*                                                                      *
524 %************************************************************************
525
526 \begin{code}
527 gen_Bounded_binds tycon
528   = if isEnumerationTyCon tycon then
529         min_bound_enum `AndMonoBinds` max_bound_enum
530     else
531         ASSERT(isSingleton data_cons)
532         min_bound_1con `AndMonoBinds` max_bound_1con
533   where
534     data_cons = tyConDataCons tycon
535     tycon_loc = getSrcLoc tycon
536
537     ----- enum-flavored: ---------------------------
538     min_bound_enum = mk_easy_FunMonoBind tycon_loc minBound_RDR [] [] (HsVar data_con_1_RDR)
539     max_bound_enum = mk_easy_FunMonoBind tycon_loc maxBound_RDR [] [] (HsVar data_con_N_RDR)
540
541     data_con_1    = head data_cons
542     data_con_N    = last data_cons
543     data_con_1_RDR = qual_orig_name data_con_1
544     data_con_N_RDR = qual_orig_name data_con_N
545
546     ----- single-constructor-flavored: -------------
547     arity          = dataConSourceArity data_con_1
548
549     min_bound_1con = mk_easy_FunMonoBind tycon_loc minBound_RDR [] [] $
550                      mk_easy_App data_con_1_RDR (nOfThem arity minBound_RDR)
551     max_bound_1con = mk_easy_FunMonoBind tycon_loc maxBound_RDR [] [] $
552                      mk_easy_App data_con_1_RDR (nOfThem arity maxBound_RDR)
553 \end{code}
554
555 %************************************************************************
556 %*                                                                      *
557 \subsubsection{Generating @Ix@ instance declarations}
558 %*                                                                      *
559 %************************************************************************
560
561 Deriving @Ix@ is only possible for enumeration types and
562 single-constructor types.  We deal with them in turn.
563
564 For an enumeration type, e.g.,
565 \begin{verbatim}
566     data Foo ... = N1 | N2 | ... | Nn
567 \end{verbatim}
568 things go not too differently from @Enum@:
569 \begin{verbatim}
570 instance ... Ix (Foo ...) where
571     range (a, b)
572       = map tag2con_Foo [con2tag_Foo a .. con2tag_Foo b]
573
574     -- or, really...
575     range (a, b)
576       = case (con2tag_Foo a) of { a# ->
577         case (con2tag_Foo b) of { b# ->
578         map tag2con_Foo (enumFromTo (I# a#) (I# b#))
579         }}
580
581     index c@(a, b) d
582       = if inRange c d
583         then case (con2tag_Foo d -# con2tag_Foo a) of
584                r# -> I# r#
585         else error "Ix.Foo.index: out of range"
586
587     inRange (a, b) c
588       = let
589             p_tag = con2tag_Foo c
590         in
591         p_tag >= con2tag_Foo a && p_tag <= con2tag_Foo b
592
593     -- or, really...
594     inRange (a, b) c
595       = case (con2tag_Foo a)   of { a_tag ->
596         case (con2tag_Foo b)   of { b_tag ->
597         case (con2tag_Foo c)   of { c_tag ->
598         if (c_tag >=# a_tag) then
599           c_tag <=# b_tag
600         else
601           False
602         }}}
603 \end{verbatim}
604 (modulo suitable case-ification to handle the unlifted tags)
605
606 For a single-constructor type (NB: this includes all tuples), e.g.,
607 \begin{verbatim}
608     data Foo ... = MkFoo a b Int Double c c
609 \end{verbatim}
610 we follow the scheme given in Figure~19 of the Haskell~1.2 report
611 (p.~147).
612
613 \begin{code}
614 gen_Ix_binds :: TyCon -> RdrNameMonoBinds
615
616 gen_Ix_binds tycon
617   = if isEnumerationTyCon tycon
618     then enum_ixes
619     else single_con_ixes
620   where
621     tycon_str = getOccString tycon
622     tycon_loc = getSrcLoc tycon
623
624     --------------------------------------------------------------
625     enum_ixes = enum_range `AndMonoBinds`
626                 enum_index `AndMonoBinds` enum_inRange
627
628     enum_range
629       = mk_easy_FunMonoBind tycon_loc range_RDR 
630                 [TuplePatIn [a_Pat, b_Pat] Boxed] [] $
631           untag_Expr tycon [(a_RDR, ah_RDR)] $
632           untag_Expr tycon [(b_RDR, bh_RDR)] $
633           HsApp (mk_easy_App map_RDR [tag2con_RDR tycon]) $
634               HsPar (enum_from_to_Expr
635                         (mk_easy_App mkInt_RDR [ah_RDR])
636                         (mk_easy_App mkInt_RDR [bh_RDR]))
637
638     enum_index
639       = mk_easy_FunMonoBind tycon_loc index_RDR 
640                 [AsPatIn c_RDR (TuplePatIn [a_Pat, wildPat] Boxed), 
641                                 d_Pat] [] (
642         HsIf (HsPar (mk_easy_App inRange_RDR [c_RDR, d_RDR])) (
643            untag_Expr tycon [(a_RDR, ah_RDR)] (
644            untag_Expr tycon [(d_RDR, dh_RDR)] (
645            let
646                 rhs = mk_easy_App mkInt_RDR [c_RDR]
647            in
648            HsCase
649              (genOpApp (HsVar dh_RDR) minusH_RDR (HsVar ah_RDR))
650              [mkSimpleMatch [VarPatIn c_RDR] rhs placeHolderType tycon_loc]
651              tycon_loc
652            ))
653         ) {-else-} (
654            HsApp (HsVar error_RDR) (HsLit (HsString (_PK_ ("Ix."++tycon_str++".index: out of range\n"))))
655         )
656         tycon_loc)
657
658     enum_inRange
659       = mk_easy_FunMonoBind tycon_loc inRange_RDR 
660           [TuplePatIn [a_Pat, b_Pat] Boxed, c_Pat] [] (
661           untag_Expr tycon [(a_RDR, ah_RDR)] (
662           untag_Expr tycon [(b_RDR, bh_RDR)] (
663           untag_Expr tycon [(c_RDR, ch_RDR)] (
664           HsIf (genOpApp (HsVar ch_RDR) geH_RDR (HsVar ah_RDR)) (
665              (genOpApp (HsVar ch_RDR) leH_RDR (HsVar bh_RDR))
666           ) {-else-} (
667              false_Expr
668           ) tycon_loc))))
669
670     --------------------------------------------------------------
671     single_con_ixes 
672       = single_con_range `AndMonoBinds`
673         single_con_index `AndMonoBinds`
674         single_con_inRange
675
676     data_con
677       = case maybeTyConSingleCon tycon of -- just checking...
678           Nothing -> panic "get_Ix_binds"
679           Just dc -> if (any isUnLiftedType (dataConOrigArgTys dc)) then
680                          error ("ERROR: Can't derive Ix for a single-constructor type with primitive argument types: "++tycon_str)
681                      else
682                          dc
683
684     con_arity    = dataConSourceArity data_con
685     data_con_RDR = qual_orig_name data_con
686
687     as_needed = take con_arity as_RDRs
688     bs_needed = take con_arity bs_RDRs
689     cs_needed = take con_arity cs_RDRs
690
691     con_pat  xs  = ConPatIn data_con_RDR (map VarPatIn xs)
692     con_expr     = mk_easy_App data_con_RDR cs_needed
693
694     --------------------------------------------------------------
695     single_con_range
696       = mk_easy_FunMonoBind tycon_loc range_RDR 
697           [TuplePatIn [con_pat as_needed, con_pat bs_needed] Boxed] [] $
698         HsDo ListComp stmts tycon_loc
699       where
700         stmts = zipWith3Equal "single_con_range" mk_qual as_needed bs_needed cs_needed
701                 ++
702                 [ResultStmt con_expr tycon_loc]
703
704         mk_qual a b c = BindStmt (VarPatIn c)
705                                  (HsApp (HsVar range_RDR) 
706                                         (ExplicitTuple [HsVar a, HsVar b] Boxed))
707                                  tycon_loc
708
709     ----------------
710     single_con_index
711       = mk_easy_FunMonoBind tycon_loc index_RDR 
712                 [TuplePatIn [con_pat as_needed, con_pat bs_needed] Boxed, 
713                  con_pat cs_needed] [range_size] (
714         foldl mk_index (HsLit (HsInt 0)) (zip3 as_needed bs_needed cs_needed))
715       where
716         mk_index multiply_by (l, u, i)
717           = genOpApp (
718                (HsApp (HsApp (HsVar index_RDR) 
719                       (ExplicitTuple [HsVar l, HsVar u] Boxed)) (HsVar i))
720            ) plus_RDR (
721                 genOpApp (
722                     (HsApp (HsVar rangeSize_RDR) 
723                            (ExplicitTuple [HsVar l, HsVar u] Boxed))
724                 ) times_RDR multiply_by
725            )
726
727         range_size
728           = mk_easy_FunMonoBind tycon_loc rangeSize_RDR 
729                         [TuplePatIn [a_Pat, b_Pat] Boxed] [] (
730                 genOpApp (
731                     (HsApp (HsApp (HsVar index_RDR) 
732                            (ExplicitTuple [a_Expr, b_Expr] Boxed)) b_Expr)
733                 ) plus_RDR (HsLit (HsInt 1)))
734
735     ------------------
736     single_con_inRange
737       = mk_easy_FunMonoBind tycon_loc inRange_RDR 
738                 [TuplePatIn [con_pat as_needed, con_pat bs_needed] Boxed, 
739                  con_pat cs_needed]
740                            [] (
741           foldl1 and_Expr (zipWith3Equal "single_con_inRange" in_range as_needed bs_needed cs_needed))
742       where
743         in_range a b c = HsApp (HsApp (HsVar inRange_RDR) 
744                                       (ExplicitTuple [HsVar a, HsVar b] Boxed)) 
745                                (HsVar c)
746 \end{code}
747
748 %************************************************************************
749 %*                                                                      *
750 \subsubsection{Generating @Read@ instance declarations}
751 %*                                                                      *
752 %************************************************************************
753
754 \begin{code}
755 gen_Read_binds :: FixityEnv -> TyCon -> RdrNameMonoBinds
756
757 gen_Read_binds get_fixity tycon
758   = reads_prec `AndMonoBinds` read_list
759   where
760     tycon_loc = getSrcLoc tycon
761     -----------------------------------------------------------------------
762     read_list = mk_easy_FunMonoBind tycon_loc readList_RDR [] []
763                   (HsApp (HsVar readList___RDR) (HsPar (HsApp (HsVar readsPrec_RDR) (HsLit (HsInt 0)))))
764     -----------------------------------------------------------------------
765     reads_prec
766       = let
767             read_con_comprehensions
768               = map read_con (tyConDataCons tycon)
769         in
770         mk_easy_FunMonoBind tycon_loc readsPrec_RDR [zz_a_Pat, b_Pat] [] (
771               foldr1 append_Expr read_con_comprehensions
772         )
773       where
774         read_con data_con   -- note: "b" is the string being "read"
775           = HsApp (
776               readParen_Expr read_paren_arg $ HsPar $
777                  HsLam (mk_easy_Match tycon_loc [c_Pat] [] $
778                         HsDo ListComp stmts tycon_loc)
779               ) (HsVar b_RDR)
780          where
781            data_con_RDR = qual_orig_name data_con
782            data_con_str = occNameUserString (getOccName data_con)
783            con_arity    = dataConSourceArity data_con
784            con_expr     = mk_easy_App data_con_RDR as_needed
785            nullary_con  = con_arity == 0
786            labels       = dataConFieldLabels data_con
787            lab_fields   = length labels
788            dc_nm        = getName data_con
789            is_infix     = isDataSymOcc (getOccName dc_nm)
790
791            as_needed    = take con_arity as_RDRs
792            bs_needed   
793              | is_infix        = take (1 + con_arity) bs_RDRs
794              | lab_fields == 0 = take con_arity bs_RDRs
795              | otherwise       = take (4*lab_fields + 1) bs_RDRs
796                                   -- (label, '=' and field)*n, (n-1)*',' + '{' + '}'
797
798            (as1:as2:_)     = as_needed
799            (bs1:bs2:bs3:_) = bs_needed
800
801            con_qual 
802              | not is_infix =
803                  BindStmt
804                   (TuplePatIn [LitPatIn (mkHsString data_con_str), d_Pat] Boxed)
805                   (HsApp (HsVar lex_RDR) c_Expr)
806                   tycon_loc
807              | otherwise    =
808                  BindStmt
809                   (TuplePatIn [LitPatIn (mkHsString data_con_str), VarPatIn bs2] Boxed)
810                   (HsApp (HsVar lex_RDR) (HsVar bs1))
811                   tycon_loc
812                 
813
814            str_qual str res draw_from =
815                BindStmt
816                   (TuplePatIn [LitPatIn (mkHsString str), VarPatIn res] Boxed)
817                   (HsApp (HsVar lex_RDR) draw_from)
818                   tycon_loc
819   
820            str_qual_paren str res draw_from =
821                BindStmt
822                   (TuplePatIn [LitPatIn (mkHsString str), VarPatIn res] Boxed)
823                   (HsApp (readParen_Expr true_Expr (HsVar lex_RDR)) draw_from)
824                   tycon_loc
825   
826            read_label f = [rd_lab, str_qual "="] 
827                             -- There might be spaces between the label and '='
828                 where
829                   rd_lab
830                    | is_op      = str_qual_paren nm
831                    | otherwise  = str_qual nm
832
833                   occ_nm  = getOccName (fieldLabelName f)
834                   is_op   = isSymOcc occ_nm
835                   nm      = occNameUserString occ_nm
836
837            field_quals
838               | is_infix  =
839                   snd (mapAccumL mk_qual_infix
840                                  c_Expr
841                                  [ (mk_read_qual lp as1, bs1, bs2)
842                                  , (mk_read_qual rp as2, bs3, bs3)
843                                  ])
844               | lab_fields == 0 =  -- common case.
845                   snd (mapAccumL mk_qual 
846                                  d_Expr 
847                                  (zipWithEqual "as_needed" 
848                                                (\ con_field draw_from -> (mk_read_qual 10 con_field,
849                                                                           draw_from))
850                                                 as_needed bs_needed))
851               | otherwise =
852                   snd $
853                   mapAccumL mk_qual d_Expr
854                         (zipEqual "bs_needed"        
855                            ((str_qual "{":
856                              concat (
857                              intersperse [str_qual ","] $
858                              zipWithEqual 
859                                 "field_quals"
860                                 (\ as b -> as ++ [b])
861                                     -- The labels
862                                 (map read_label labels)
863                                     -- The fields
864                                 (map (mk_read_qual 10) as_needed))) ++ [str_qual "}"])
865                             bs_needed)
866
867            mk_qual_infix draw_from (f, str_left, str_left2) =
868                 (HsVar str_left2,       -- what to draw from down the line...
869                  f str_left draw_from)
870
871            mk_qual draw_from (f, str_left) =
872                 (HsVar str_left,        -- what to draw from down the line...
873                  f str_left draw_from)
874
875            mk_read_qual p con_field res draw_from =
876               BindStmt
877                  (TuplePatIn [VarPatIn con_field, VarPatIn res] Boxed)
878                  (HsApp (HsApp (HsVar readsPrec_RDR) (HsLit (HsInt p))) draw_from)
879                  tycon_loc
880
881            result_expr = ExplicitTuple [con_expr, if null bs_needed 
882                                                     then d_Expr 
883                                                     else HsVar (last bs_needed)] Boxed
884
885            [lp,rp] = getLRPrecs is_infix get_fixity dc_nm
886
887            quals
888             | is_infix  = let (h:t) = field_quals in (h:con_qual:t)
889             | otherwise = con_qual:field_quals
890
891            stmts = quals ++ [ResultStmt result_expr tycon_loc]
892                 
893             {-
894               c.f. Figure 18 in Haskell 1.1 report.
895             -}
896            paren_prec_limit
897              | not is_infix  = defaultPrecedence
898              | otherwise     = getPrecedence get_fixity dc_nm
899
900            read_paren_arg   -- parens depend on precedence...
901             | nullary_con  = false_Expr -- it's optional.
902             | otherwise    = HsPar (genOpApp zz_a_Expr gt_RDR (HsLit (HsInt paren_prec_limit)))
903 \end{code}
904
905 %************************************************************************
906 %*                                                                      *
907 \subsubsection{Generating @Show@ instance declarations}
908 %*                                                                      *
909 %************************************************************************
910
911 \begin{code}
912 gen_Show_binds :: FixityEnv -> TyCon -> RdrNameMonoBinds
913
914 gen_Show_binds get_fixity tycon
915   = shows_prec `AndMonoBinds` show_list
916   where
917     tycon_loc = getSrcLoc tycon
918     -----------------------------------------------------------------------
919     show_list = mk_easy_FunMonoBind tycon_loc showList_RDR [] []
920                   (HsApp (HsVar showList___RDR) (HsPar (HsApp (HsVar showsPrec_RDR) (HsLit (HsInt 0)))))
921     -----------------------------------------------------------------------
922     shows_prec = mk_FunMonoBind tycon_loc showsPrec_RDR (map pats_etc (tyConDataCons tycon))
923       where
924         pats_etc data_con
925           | nullary_con =  -- skip the showParen junk...
926              ASSERT(null bs_needed)
927              ([wildPat, con_pat], show_con)
928           | otherwise   =
929              ([a_Pat, con_pat],
930                   showParen_Expr (HsPar (genOpApp a_Expr ge_RDR (HsLit (HsInt paren_prec_limit))))
931                                  (HsPar (nested_compose_Expr show_thingies)))
932             where
933              data_con_RDR = qual_orig_name data_con
934              con_arity    = dataConSourceArity data_con
935              bs_needed    = take con_arity bs_RDRs
936              con_pat      = ConPatIn data_con_RDR (map VarPatIn bs_needed)
937              nullary_con  = con_arity == 0
938              labels       = dataConFieldLabels data_con
939              lab_fields   = length labels
940
941              dc_nm          = getName data_con
942              dc_occ_nm      = getOccName data_con
943              dc_occ_nm_str  = occNameUserString dc_occ_nm
944
945              is_infix     = isDataSymOcc dc_occ_nm
946
947
948              show_con
949                | is_infix  = mk_showString_app (' ':dc_occ_nm_str)
950                | otherwise = mk_showString_app (dc_occ_nm_str ++ space_ocurly_maybe)
951                  where
952                   space_ocurly_maybe
953                     | nullary_con     = ""
954                     | lab_fields == 0 = " "
955                     | otherwise       = "{"
956                  
957
958              show_all con fs@(x:xs)
959                 | is_infix  = x:con:xs
960                 | otherwise = 
961                   let
962                     ccurly_maybe 
963                       | lab_fields > 0  = [mk_showString_app "}"]
964                       | otherwise       = []
965                   in
966                   con:fs ++ ccurly_maybe
967
968              show_thingies = show_all show_con real_show_thingies_with_labs
969                 
970              show_label l = mk_showString_app (the_name ++ "=")
971                  where
972                    occ_nm   = getOccName (fieldLabelName l)
973                     -- legal, but rare.
974                    is_op    = isSymOcc occ_nm
975                    the_name 
976                      | is_op     = '(':nm ++ ")"
977                      | otherwise = nm
978
979                    nm       = occNameUserString occ_nm
980                 
981
982              mk_showString_app str = HsApp (HsVar showString_RDR)
983                                            (HsLit (mkHsString str))
984
985              prec_cons = getLRPrecs is_infix get_fixity dc_nm
986
987              real_show_thingies
988                 | is_infix  = 
989                      [ HsApp (HsApp (HsVar showsPrec_RDR) (HsLit (HsInt p))) (HsVar b)
990                      | (p,b) <- zip prec_cons bs_needed ]
991                 | otherwise =
992                      [ HsApp (HsApp (HsVar showsPrec_RDR) (HsLit (HsInt 10))) (HsVar b)
993                      | b <- bs_needed ]
994
995              real_show_thingies_with_labs
996                 | lab_fields == 0 = intersperse (HsVar showSpace_RDR) real_show_thingies
997                 | otherwise       = --Assumption: no of fields == no of labelled fields 
998                                      --            (and in same order)
999                     concat $
1000                     intersperse ([mk_showString_app ","]) $ -- Using SLIT()s containing ,s spells trouble.
1001                     zipWithEqual "gen_Show_binds"
1002                                  (\ a b -> [a,b])
1003                                  (map show_label labels) 
1004                                  real_show_thingies
1005                                
1006               {-
1007                 c.f. Figure 16 and 17 in Haskell 1.1 report
1008               -}  
1009              paren_prec_limit
1010                 | not is_infix = defaultPrecedence + 1
1011                 | otherwise    = getPrecedence get_fixity dc_nm + 1
1012
1013 \end{code}
1014
1015 \begin{code}
1016 getLRPrecs :: Bool -> FixityEnv -> Name -> [Integer]
1017 getLRPrecs is_infix get_fixity nm = [lp, rp]
1018     where
1019      {-
1020         Figuring out the fixities of the arguments to a constructor,
1021         cf. Figures 16-18 in Haskell 1.1 report.
1022      -}
1023      (con_left_assoc, con_right_assoc) = isLRAssoc get_fixity nm
1024      paren_con_prec = getPrecedence get_fixity nm
1025
1026      lp
1027       | not is_infix   = defaultPrecedence + 1
1028       | con_left_assoc = paren_con_prec
1029       | otherwise      = paren_con_prec + 1
1030                   
1031      rp
1032       | not is_infix    = defaultPrecedence + 1
1033       | con_right_assoc = paren_con_prec
1034       | otherwise       = paren_con_prec + 1
1035                   
1036 defaultPrecedence :: Integer
1037 defaultPrecedence = fromInt maxPrecedence
1038
1039 getPrecedence :: FixityEnv -> Name -> Integer
1040 getPrecedence get_fixity nm 
1041    = case lookupFixity get_fixity nm of
1042         Fixity x _ -> fromInt x
1043
1044 isLRAssoc :: FixityEnv -> Name -> (Bool, Bool)
1045 isLRAssoc get_fixity nm =
1046      case lookupFixity get_fixity nm of
1047        Fixity _ InfixN -> (False, False)
1048        Fixity _ InfixR -> (False, True)
1049        Fixity _ InfixL -> (True,  False)
1050 \end{code}
1051
1052
1053 %************************************************************************
1054 %*                                                                      *
1055 \subsection{Generating extra binds (@con2tag@ and @tag2con@)}
1056 %*                                                                      *
1057 %************************************************************************
1058
1059 \begin{verbatim}
1060 data Foo ... = ...
1061
1062 con2tag_Foo :: Foo ... -> Int#
1063 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
1064 maxtag_Foo  :: Int              -- ditto (NB: not unlifted)
1065 \end{verbatim}
1066
1067 The `tags' here start at zero, hence the @fIRST_TAG@ (currently one)
1068 fiddling around.
1069
1070 \begin{code}
1071 data TagThingWanted
1072   = GenCon2Tag | GenTag2Con | GenMaxTag
1073
1074 gen_tag_n_con_monobind
1075     :: (RdrName,            -- (proto)Name for the thing in question
1076         TyCon,              -- tycon in question
1077         TagThingWanted)
1078     -> RdrNameMonoBinds
1079
1080 gen_tag_n_con_monobind (rdr_name, tycon, GenCon2Tag)
1081   | lots_of_constructors
1082   = mk_FunMonoBind (getSrcLoc tycon) rdr_name 
1083         [([VarPatIn a_RDR], HsApp getTag_Expr a_Expr)]
1084
1085   | otherwise
1086   = mk_FunMonoBind (getSrcLoc tycon) rdr_name (map mk_stuff (tyConDataCons tycon))
1087
1088   where
1089     lots_of_constructors = tyConFamilySize tycon > mAX_FAMILY_SIZE_FOR_VEC_RETURNS
1090
1091     mk_stuff :: DataCon -> ([RdrNamePat], RdrNameHsExpr)
1092     mk_stuff var
1093       = ([pat], HsLit (HsIntPrim (toInteger ((dataConTag var) - fIRST_TAG))))
1094       where
1095         pat    = ConPatIn var_RDR (nOfThem (dataConSourceArity var) WildPatIn)
1096         var_RDR = qual_orig_name var
1097
1098 gen_tag_n_con_monobind (rdr_name, tycon, GenTag2Con)
1099   = mk_FunMonoBind (getSrcLoc tycon) rdr_name 
1100         [([ConPatIn mkInt_RDR [VarPatIn a_RDR]], 
1101            ExprWithTySig (HsApp tagToEnum_Expr a_Expr) 
1102                          (HsTyVar (qual_orig_name tycon)))]
1103
1104 gen_tag_n_con_monobind (rdr_name, tycon, GenMaxTag)
1105   = mk_easy_FunMonoBind (getSrcLoc tycon) 
1106                 rdr_name [] [] (HsApp (HsVar mkInt_RDR) (HsLit (HsIntPrim max_tag)))
1107   where
1108     max_tag =  case (tyConDataCons tycon) of
1109                  data_cons -> toInteger ((length data_cons) - fIRST_TAG)
1110
1111 \end{code}
1112
1113 %************************************************************************
1114 %*                                                                      *
1115 \subsection{Utility bits for generating bindings}
1116 %*                                                                      *
1117 %************************************************************************
1118
1119 @mk_easy_FunMonoBind fun pats binds expr@ generates:
1120 \begin{verbatim}
1121     fun pat1 pat2 ... patN = expr where binds
1122 \end{verbatim}
1123
1124 @mk_FunMonoBind fun [([p1a, p1b, ...], e1), ...]@ is for
1125 multi-clause definitions; it generates:
1126 \begin{verbatim}
1127     fun p1a p1b ... p1N = e1
1128     fun p2a p2b ... p2N = e2
1129     ...
1130     fun pMa pMb ... pMN = eM
1131 \end{verbatim}
1132
1133 \begin{code}
1134 mk_easy_FunMonoBind :: SrcLoc -> RdrName -> [RdrNamePat]
1135                     -> [RdrNameMonoBinds] -> RdrNameHsExpr
1136                     -> RdrNameMonoBinds
1137
1138 mk_easy_FunMonoBind loc fun pats binds expr
1139   = FunMonoBind fun False{-not infix-} [mk_easy_Match loc pats binds expr] loc
1140
1141 mk_easy_Match loc pats binds expr
1142   = mk_match loc pats expr (mkMonoBind (andMonoBindList binds) [] Recursive)
1143         -- The renamer expects everything in its input to be a
1144         -- "recursive" MonoBinds, and it is its job to sort things out
1145         -- from there.
1146
1147 mk_FunMonoBind  :: SrcLoc -> RdrName
1148                 -> [([RdrNamePat], RdrNameHsExpr)]
1149                 -> RdrNameMonoBinds
1150
1151 mk_FunMonoBind loc fun [] = panic "TcGenDeriv:mk_FunMonoBind"
1152 mk_FunMonoBind loc fun pats_and_exprs
1153   = FunMonoBind fun False{-not infix-}
1154                 [ mk_match loc p e EmptyBinds | (p,e) <-pats_and_exprs ]
1155                 loc
1156
1157 mk_match loc pats expr binds
1158   = Match (map paren pats) Nothing 
1159           (GRHSs (unguardedRHS expr loc) binds placeHolderType)
1160   where
1161     paren p@(VarPatIn _) = p
1162     paren other_p        = ParPatIn other_p
1163 \end{code}
1164
1165 \begin{code}
1166 mk_easy_App f xs = foldl HsApp (HsVar f) (map HsVar xs)
1167 \end{code}
1168
1169 ToDo: Better SrcLocs.
1170
1171 \begin{code}
1172 compare_gen_Case ::
1173           RdrName
1174           -> RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
1175           -> RdrNameHsExpr -> RdrNameHsExpr
1176           -> RdrNameHsExpr
1177 careful_compare_Case :: -- checks for primitive types...
1178           Type
1179           -> RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
1180           -> RdrNameHsExpr -> RdrNameHsExpr
1181           -> RdrNameHsExpr
1182
1183 cmp_eq_Expr a b = HsApp (HsApp (HsVar cmp_eq_RDR) a) b
1184         -- Was: compare_gen_Case cmp_eq_RDR
1185
1186 compare_gen_Case fun lt eq gt a b
1187   = HsCase (HsPar (HsApp (HsApp (HsVar fun) a) b)) {-of-}
1188       [mkSimpleMatch [ConPatIn ltTag_RDR []] lt placeHolderType generatedSrcLoc,
1189        mkSimpleMatch [ConPatIn eqTag_RDR []] eq placeHolderType generatedSrcLoc,
1190        mkSimpleMatch [ConPatIn gtTag_RDR []] gt placeHolderType generatedSrcLoc]
1191       generatedSrcLoc
1192
1193 careful_compare_Case ty lt eq gt a b
1194   | not (isUnLiftedType ty) =
1195        compare_gen_Case compare_RDR lt eq gt a b
1196   | otherwise               =
1197          -- we have to do something special for primitive things...
1198        HsIf (genOpApp a relevant_eq_op b)
1199             eq
1200             (HsIf (genOpApp a relevant_lt_op b) lt gt generatedSrcLoc)
1201             generatedSrcLoc
1202   where
1203     relevant_eq_op = assoc_ty_id eq_op_tbl ty
1204     relevant_lt_op = assoc_ty_id lt_op_tbl ty
1205
1206 assoc_ty_id tyids ty 
1207   = if null res then panic "assoc_ty"
1208     else head res
1209   where
1210     res = [id | (ty',id) <- tyids, ty `tcEqType` ty']
1211
1212 eq_op_tbl =
1213     [(charPrimTy,       eqH_Char_RDR)
1214     ,(intPrimTy,        eqH_Int_RDR)
1215     ,(wordPrimTy,       eqH_Word_RDR)
1216     ,(addrPrimTy,       eqH_Addr_RDR)
1217     ,(floatPrimTy,      eqH_Float_RDR)
1218     ,(doublePrimTy,     eqH_Double_RDR)
1219     ]
1220
1221 lt_op_tbl =
1222     [(charPrimTy,       ltH_Char_RDR)
1223     ,(intPrimTy,        ltH_Int_RDR)
1224     ,(wordPrimTy,       ltH_Word_RDR)
1225     ,(addrPrimTy,       ltH_Addr_RDR)
1226     ,(floatPrimTy,      ltH_Float_RDR)
1227     ,(doublePrimTy,     ltH_Double_RDR)
1228     ]
1229
1230 -----------------------------------------------------------------------
1231
1232 and_Expr, append_Expr :: RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
1233
1234 and_Expr    a b = genOpApp a and_RDR    b
1235 append_Expr a b = genOpApp a append_RDR b
1236
1237 -----------------------------------------------------------------------
1238
1239 eq_Expr :: Type -> RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
1240 eq_Expr ty a b = genOpApp a eq_op b
1241  where
1242    eq_op
1243     | not (isUnLiftedType ty) = eq_RDR
1244     | otherwise               =
1245          -- we have to do something special for primitive things...
1246         assoc_ty_id eq_op_tbl ty
1247
1248 \end{code}
1249
1250 \begin{code}
1251 untag_Expr :: TyCon -> [(RdrName, RdrName)] -> RdrNameHsExpr -> RdrNameHsExpr
1252 untag_Expr tycon [] expr = expr
1253 untag_Expr tycon ((untag_this, put_tag_here) : more) expr
1254   = HsCase (HsPar (HsApp (con2tag_Expr tycon) (HsVar untag_this))) {-of-}
1255       [mkSimpleMatch [VarPatIn put_tag_here] (untag_Expr tycon more expr) placeHolderType generatedSrcLoc]
1256       generatedSrcLoc
1257
1258 cmp_tags_Expr :: RdrName                -- Comparison op
1259              -> RdrName -> RdrName      -- Things to compare
1260              -> RdrNameHsExpr           -- What to return if true
1261              -> RdrNameHsExpr           -- What to return if false
1262              -> RdrNameHsExpr
1263
1264 cmp_tags_Expr op a b true_case false_case
1265   = HsIf (genOpApp (HsVar a) op (HsVar b)) true_case false_case generatedSrcLoc
1266
1267 enum_from_to_Expr
1268         :: RdrNameHsExpr -> RdrNameHsExpr
1269         -> RdrNameHsExpr
1270 enum_from_then_to_Expr
1271         :: RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
1272         -> RdrNameHsExpr
1273
1274 enum_from_to_Expr      f   t2 = HsApp (HsApp (HsVar enumFromTo_RDR) f) t2
1275 enum_from_then_to_Expr f t t2 = HsApp (HsApp (HsApp (HsVar enumFromThenTo_RDR) f) t) t2
1276
1277 showParen_Expr, readParen_Expr
1278         :: RdrNameHsExpr -> RdrNameHsExpr
1279         -> RdrNameHsExpr
1280
1281 showParen_Expr e1 e2 = HsApp (HsApp (HsVar showParen_RDR) e1) e2
1282 readParen_Expr e1 e2 = HsApp (HsApp (HsVar readParen_RDR) e1) e2
1283
1284 nested_compose_Expr :: [RdrNameHsExpr] -> RdrNameHsExpr
1285
1286 nested_compose_Expr [e] = parenify e
1287 nested_compose_Expr (e:es)
1288   = HsApp (HsApp (HsVar compose_RDR) (parenify e)) (nested_compose_Expr es)
1289
1290 -- impossible_Expr is used in case RHSs that should never happen.
1291 -- We generate these to keep the desugarer from complaining that they *might* happen!
1292 impossible_Expr = HsApp (HsVar error_RDR) (HsLit (HsString (_PK_ "Urk! in TcGenDeriv")))
1293
1294 -- illegal_Expr is used when signalling error conditions in the RHS of a derived
1295 -- method. It is currently only used by Enum.{succ,pred}
1296 illegal_Expr meth tp msg = 
1297    HsApp (HsVar error_RDR) (HsLit (HsString (_PK_ (meth ++ '{':tp ++ "}: " ++ msg))))
1298
1299 -- illegal_toEnum_tag is an extended version of illegal_Expr, which also allows you
1300 -- to include the value of a_RDR in the error string.
1301 illegal_toEnum_tag tp maxtag =
1302    HsApp (HsVar error_RDR) 
1303          (HsApp (HsApp (HsVar append_RDR)
1304                        (HsLit (HsString (_PK_ ("toEnum{" ++ tp ++ "}: tag (")))))
1305                        (HsApp (HsApp (HsApp 
1306                            (HsVar showsPrec_RDR)
1307                            (HsLit (HsInt 0)))
1308                            (HsVar a_RDR))
1309                            (HsApp (HsApp 
1310                                (HsVar append_RDR)
1311                                (HsLit (HsString (_PK_ ") is outside of enumeration's range (0,"))))
1312                                (HsApp (HsApp (HsApp 
1313                                         (HsVar showsPrec_RDR)
1314                                         (HsLit (HsInt 0)))
1315                                         (HsVar maxtag))
1316                                         (HsLit (HsString (_PK_ ")")))))))
1317
1318 parenify e@(HsVar _) = e
1319 parenify e           = HsPar e
1320
1321 -- genOpApp wraps brackets round the operator application, so that the
1322 -- renamer won't subsequently try to re-associate it. 
1323 -- For some reason the renamer doesn't reassociate it right, and I can't
1324 -- be bothered to find out why just now.
1325
1326 genOpApp e1 op e2 = mkHsOpApp e1 op e2
1327 \end{code}
1328
1329 \begin{code}
1330 qual_orig_name n = nameRdrName (getName n)
1331 varUnqual n      = mkUnqual varName n
1332
1333 zz_a_RDR        = varUnqual SLIT("_a")
1334 a_RDR           = varUnqual SLIT("a")
1335 b_RDR           = varUnqual SLIT("b")
1336 c_RDR           = varUnqual SLIT("c")
1337 d_RDR           = varUnqual SLIT("d")
1338 ah_RDR          = varUnqual SLIT("a#")
1339 bh_RDR          = varUnqual SLIT("b#")
1340 ch_RDR          = varUnqual SLIT("c#")
1341 dh_RDR          = varUnqual SLIT("d#")
1342 cmp_eq_RDR      = varUnqual SLIT("cmp_eq")
1343 rangeSize_RDR   = varUnqual SLIT("rangeSize")
1344
1345 as_RDRs         = [ varUnqual (_PK_ ("a"++show i)) | i <- [(1::Int) .. ] ]
1346 bs_RDRs         = [ varUnqual (_PK_ ("b"++show i)) | i <- [(1::Int) .. ] ]
1347 cs_RDRs         = [ varUnqual (_PK_ ("c"++show i)) | i <- [(1::Int) .. ] ]
1348
1349 mkHsString s = HsString (_PK_ s)
1350
1351 zz_a_Expr       = HsVar zz_a_RDR
1352 a_Expr          = HsVar a_RDR
1353 b_Expr          = HsVar b_RDR
1354 c_Expr          = HsVar c_RDR
1355 d_Expr          = HsVar d_RDR
1356 ltTag_Expr      = HsVar ltTag_RDR
1357 eqTag_Expr      = HsVar eqTag_RDR
1358 gtTag_Expr      = HsVar gtTag_RDR
1359 false_Expr      = HsVar false_RDR
1360 true_Expr       = HsVar true_RDR
1361
1362 getTag_Expr     = HsVar getTag_RDR
1363 tagToEnum_Expr  = HsVar tagToEnumH_RDR
1364 con2tag_Expr tycon = HsVar (con2tag_RDR tycon)
1365
1366 wildPat         = WildPatIn
1367 zz_a_Pat        = VarPatIn zz_a_RDR
1368 a_Pat           = VarPatIn a_RDR
1369 b_Pat           = VarPatIn b_RDR
1370 c_Pat           = VarPatIn c_RDR
1371 d_Pat           = VarPatIn d_RDR
1372
1373 con2tag_RDR, tag2con_RDR, maxtag_RDR :: TyCon -> RdrName
1374
1375 con2tag_RDR tycon = varUnqual (_PK_ ("con2tag_" ++ occNameString (getOccName tycon) ++ "#"))
1376 tag2con_RDR tycon = varUnqual (_PK_ ("tag2con_" ++ occNameString (getOccName tycon) ++ "#"))
1377 maxtag_RDR tycon  = varUnqual (_PK_ ("maxtag_"  ++ occNameString (getOccName tycon) ++ "#"))
1378 \end{code}