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