2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[TcGenDeriv]{Generating derived instance declarations}
6 This module is nominally ``subordinate'' to @TcDeriv@, which is the
7 ``official'' interface to deriving-related things.
9 This is where we do all the grimy bindings' generation.
12 #include "HsVersions.h"
23 gen_tag_n_con_monobind,
25 con2tag_RDR, tag2con_RDR, maxtag_RDR,
31 IMPORT_1_3(List(partition))
33 import HsSyn ( HsBinds(..), Bind(..), MonoBinds(..), Match(..), GRHSsAndBinds(..),
34 GRHS(..), HsExpr(..), HsLit(..), InPat(..), Stmt(..), DoOrListComp(..),
35 ArithSeqInfo, Sig, HsType, FixityDecl, Fixity, Fake )
36 import RdrHsSyn ( RdrName(..), varQual, varUnqual, mkOpApp,
37 SYN_IE(RdrNameMonoBinds), SYN_IE(RdrNameHsExpr), SYN_IE(RdrNamePat)
39 -- import RnHsSyn ( RenamedFixityDecl(..) )
41 import Id ( GenId, dataConNumFields, isNullaryDataCon, dataConTag,
42 dataConRawArgTys, fIRST_TAG,
43 isDataCon, SYN_IE(DataCon), SYN_IE(ConTag) )
44 import Maybes ( maybeToBool )
45 import Name ( getOccString, getOccName, getSrcLoc, occNameString, modAndOcc, OccName, Name )
47 import PrimOp ( PrimOp(..) )
48 import PrelInfo -- Lots of RdrNames
49 import SrcLoc ( mkGeneratedSrcLoc )
50 import TyCon ( TyCon, tyConDataCons, isEnumerationTyCon, maybeTyConSingleCon )
51 import Type ( eqTy, isPrimType )
52 import TysPrim ( charPrimTy, intPrimTy, wordPrimTy, addrPrimTy,
53 floatPrimTy, doublePrimTy
55 import Util ( mapAccumL, zipEqual, zipWith3Equal, nOfThem, panic, assertPanic )
58 %************************************************************************
60 \subsection{Generating code, by derivable class}
62 %************************************************************************
64 %************************************************************************
66 \subsubsection{Generating @Eq@ instance declarations}
68 %************************************************************************
70 Here are the heuristics for the code we generate for @Eq@:
73 Let's assume we have a data type with some (possibly zero) nullary
74 data constructors and some ordinary, non-nullary ones (the rest,
75 also possibly zero of them). Here's an example, with both \tr{N}ullary
76 and \tr{O}rdinary data cons.
78 data Foo ... = N1 | N2 ... | Nn | O1 a b | O2 Int | O3 Double b b | ...
82 For the ordinary constructors (if any), we emit clauses to do The
86 (==) (O1 a1 b1) (O1 a2 b2) = a1 == a2 && b1 == b2
87 (==) (O2 a1) (O2 a2) = a1 == a2
88 (==) (O3 a1 b1 c1) (O3 a2 b2 c2) = a1 == a2 && b1 == b2 && c1 == c2
91 Note: if we're comparing unboxed things, e.g., if \tr{a1} and
92 \tr{a2} are \tr{Float#}s, then we have to generate
94 case (a1 `eqFloat#` a2) of
97 for that particular test.
100 If there are any nullary constructors, we emit a catch-all clause of
104 (==) a b = case (con2tag_Foo a) of { a# ->
105 case (con2tag_Foo b) of { b# ->
106 case (a# ==# b#) of {
111 If there aren't any nullary constructors, we emit a simpler
118 For the @(/=)@ method, we normally just use the default method.
120 If the type is an enumeration type, we could/may/should? generate
121 special code that calls @con2tag_Foo@, much like for @(==)@ shown
125 We thought about doing this: If we're also deriving @Ord@ for this
128 instance ... Eq (Foo ...) where
129 (==) a b = case (compare a b) of { _LT -> False; _EQ -> True ; _GT -> False}
130 (/=) a b = case (compare a b) of { _LT -> True ; _EQ -> False; _GT -> True }
132 However, that requires that \tr{Ord <whatever>} was put in the context
133 for the instance decl, which it probably wasn't, so the decls
134 produced don't get through the typechecker.
138 gen_Eq_binds :: TyCon -> RdrNameMonoBinds
142 tycon_loc = getSrcLoc tycon
143 (nullary_cons, nonnullary_cons)
144 = partition isNullaryDataCon (tyConDataCons tycon)
147 = if (null nullary_cons) then
148 case maybeTyConSingleCon tycon of
150 Nothing -> -- if cons don't match, then False
151 [([a_Pat, b_Pat], false_Expr)]
152 else -- calc. and compare the tags
154 untag_Expr tycon [(a_RDR,ah_RDR), (b_RDR,bh_RDR)]
155 (cmp_tags_Expr eqH_Int_RDR ah_RDR bh_RDR true_Expr false_Expr))]
157 mk_FunMonoBind tycon_loc eq_RDR ((map pats_etc nonnullary_cons) ++ rest)
159 mk_easy_FunMonoBind tycon_loc ne_RDR [a_Pat, b_Pat] [] (
160 HsApp (HsVar not_RDR) (HsPar (mk_easy_App eq_RDR [a_RDR, b_RDR])))
162 ------------------------------------------------------------------
165 con1_pat = ConPatIn data_con_RDR (map VarPatIn as_needed)
166 con2_pat = ConPatIn data_con_RDR (map VarPatIn bs_needed)
168 data_con_RDR = qual_orig_name data_con
169 con_arity = length tys_needed
170 as_needed = take con_arity as_RDRs
171 bs_needed = take con_arity bs_RDRs
172 tys_needed = dataConRawArgTys data_con
174 ([con1_pat, con2_pat], nested_eq_expr tys_needed as_needed bs_needed)
176 nested_eq_expr [] [] [] = true_Expr
177 nested_eq_expr tys as bs
178 = foldl1 and_Expr (zipWith3Equal "nested_eq" nested_eq tys as bs)
180 nested_eq ty a b = HsPar (eq_Expr ty (HsVar a) (HsVar b))
183 %************************************************************************
185 \subsubsection{Generating @Ord@ instance declarations}
187 %************************************************************************
189 For a derived @Ord@, we concentrate our attentions on @compare@
191 compare :: a -> a -> Ordering
192 data Ordering = LT | EQ | GT deriving ()
195 We will use the same example data type as above:
197 data Foo ... = N1 | N2 ... | Nn | O1 a b | O2 Int | O3 Double b b | ...
202 We do all the other @Ord@ methods with calls to @compare@:
204 instance ... (Ord <wurble> <wurble>) where
205 a < b = case (compare a b) of { LT -> True; EQ -> False; GT -> False }
206 a <= b = case (compare a b) of { LT -> True; EQ -> True; GT -> False }
207 a >= b = case (compare a b) of { LT -> False; EQ -> True; GT -> True }
208 a > b = case (compare a b) of { LT -> False; EQ -> False; GT -> True }
210 max a b = case (compare a b) of { LT -> b; EQ -> a; GT -> a }
211 min a b = case (compare a b) of { LT -> a; EQ -> b; GT -> b }
213 -- compare to come...
217 @compare@ always has two parts. First, we use the compared
218 data-constructors' tags to deal with the case of different
221 compare a b = case (con2tag_Foo a) of { a# ->
222 case (con2tag_Foo b) of { b# ->
223 case (a# ==# b#) of {
225 False -> case (a# <# b#) of
230 cmp_eq = ... to come ...
234 We are only left with the ``help'' function @cmp_eq@, to deal with
235 comparing data constructors with the same tag.
237 For the ordinary constructors (if any), we emit the sorta-obvious
238 compare-style stuff; for our example:
240 cmp_eq (O1 a1 b1) (O1 a2 b2)
241 = case (compare a1 a2) of { LT -> LT; EQ -> compare b1 b2; GT -> GT }
243 cmp_eq (O2 a1) (O2 a2)
246 cmp_eq (O3 a1 b1 c1) (O3 a2 b2 c2)
247 = case (compare a1 a2) of {
250 EQ -> case compare b1 b2 of {
258 Again, we must be careful about unboxed comparisons. For example,
259 if \tr{a1} and \tr{a2} were \tr{Int#}s in the 2nd example above, we'd need to
262 cmp_eq lt eq gt (O2 a1) (O2 a2)
264 -- or maybe the unfolded equivalent
268 For the remaining nullary constructors, we already know that the
276 gen_Ord_binds :: TyCon -> RdrNameMonoBinds
279 = defaulted `AndMonoBinds` compare
281 tycon_loc = getSrcLoc tycon
282 --------------------------------------------------------------------
283 compare = mk_easy_FunMonoBind tycon_loc compare_RDR
286 (if maybeToBool (maybeTyConSingleCon tycon) then
287 cmp_eq_Expr ltTag_Expr eqTag_Expr gtTag_Expr a_Expr b_Expr
289 untag_Expr tycon [(a_RDR, ah_RDR), (b_RDR, bh_RDR)]
290 (cmp_tags_Expr eqH_Int_RDR ah_RDR bh_RDR
291 -- True case; they are equal
292 -- If an enumeration type we are done; else
293 -- recursively compare their components
294 (if isEnumerationTyCon tycon then
297 cmp_eq_Expr ltTag_Expr eqTag_Expr gtTag_Expr a_Expr b_Expr
299 -- False case; they aren't equal
300 -- So we need to do a less-than comparison on the tags
301 (cmp_tags_Expr ltH_Int_RDR ah_RDR bh_RDR ltTag_Expr gtTag_Expr)))
303 (nullary_cons, nonnullary_cons)
304 = partition isNullaryDataCon (tyConDataCons tycon)
307 = mk_FunMonoBind tycon_loc cmp_eq_RDR (map pats_etc nonnullary_cons ++
308 [([WildPatIn, WildPatIn], default_rhs)])
311 = ([con1_pat, con2_pat],
312 nested_compare_expr tys_needed as_needed bs_needed)
314 con1_pat = ConPatIn data_con_RDR (map VarPatIn as_needed)
315 con2_pat = ConPatIn data_con_RDR (map VarPatIn bs_needed)
317 data_con_RDR = qual_orig_name data_con
318 con_arity = length tys_needed
319 as_needed = take con_arity as_RDRs
320 bs_needed = take con_arity bs_RDRs
321 tys_needed = dataConRawArgTys data_con
323 nested_compare_expr [ty] [a] [b]
324 = careful_compare_Case ty ltTag_Expr eqTag_Expr gtTag_Expr (HsVar a) (HsVar b)
326 nested_compare_expr (ty:tys) (a:as) (b:bs)
327 = let eq_expr = nested_compare_expr tys as bs
328 in careful_compare_Case ty ltTag_Expr eq_expr gtTag_Expr (HsVar a) (HsVar b)
330 default_rhs | null nullary_cons = impossible_Expr -- Keep desugarer from complaining about
331 -- inexhaustive patterns
332 | otherwise = eqTag_Expr -- Some nullary constructors;
333 -- Tags are equal, no args => return EQ
334 --------------------------------------------------------------------
336 defaulted = foldr1 AndMonoBinds [lt, le, ge, gt, max_, min_]
338 lt = mk_easy_FunMonoBind mkGeneratedSrcLoc lt_RDR [a_Pat, b_Pat] [] (
339 compare_Case true_Expr false_Expr false_Expr a_Expr b_Expr)
340 le = mk_easy_FunMonoBind mkGeneratedSrcLoc le_RDR [a_Pat, b_Pat] [] (
341 compare_Case true_Expr true_Expr false_Expr a_Expr b_Expr)
342 ge = mk_easy_FunMonoBind mkGeneratedSrcLoc ge_RDR [a_Pat, b_Pat] [] (
343 compare_Case false_Expr true_Expr true_Expr a_Expr b_Expr)
344 gt = mk_easy_FunMonoBind mkGeneratedSrcLoc gt_RDR [a_Pat, b_Pat] [] (
345 compare_Case false_Expr false_Expr true_Expr a_Expr b_Expr)
347 max_ = mk_easy_FunMonoBind mkGeneratedSrcLoc max_RDR [a_Pat, b_Pat] [] (
348 compare_Case b_Expr a_Expr a_Expr a_Expr b_Expr)
349 min_ = mk_easy_FunMonoBind mkGeneratedSrcLoc min_RDR [a_Pat, b_Pat] [] (
350 compare_Case a_Expr b_Expr b_Expr a_Expr b_Expr)
353 %************************************************************************
355 \subsubsection{Generating @Enum@ instance declarations}
357 %************************************************************************
359 @Enum@ can only be derived for enumeration types. For a type
361 data Foo ... = N1 | N2 | ... | Nn
364 we use both @con2tag_Foo@ and @tag2con_Foo@ functions, as well as a
365 @maxtag_Foo@ variable (all generated by @gen_tag_n_con_binds@).
368 instance ... Enum (Foo ...) where
369 enumFrom a = map tag2con_Foo [con2tag_Foo a .. maxtag_Foo]
373 = case con2tag_Foo a of
374 a# -> map tag2con_Foo (enumFromTo (I# a#) maxtag_Foo)
377 = map tag2con_Foo [con2tag_Foo a, con2tag_Foo b .. maxtag_Foo]
381 = case con2tag_Foo a of { a# ->
382 case con2tag_Foo b of { b# ->
383 map tag2con_Foo (enumFromThenTo (I# a#) (I# b#) maxtag_Foo)
387 For @enumFromTo@ and @enumFromThenTo@, we use the default methods.
390 gen_Enum_binds :: TyCon -> RdrNameMonoBinds
393 = enum_from `AndMonoBinds`
394 enum_from_then `AndMonoBinds`
397 tycon_loc = getSrcLoc tycon
399 = mk_easy_FunMonoBind tycon_loc enumFrom_RDR [a_Pat] [] $
400 untag_Expr tycon [(a_RDR, ah_RDR)] $
401 HsApp (mk_easy_App map_RDR [tag2con_RDR tycon]) $
402 HsPar (enum_from_to_Expr
403 (mk_easy_App mkInt_RDR [ah_RDR])
404 (HsVar (maxtag_RDR tycon)))
407 = mk_easy_FunMonoBind tycon_loc enumFromThen_RDR [a_Pat, b_Pat] [] $
408 untag_Expr tycon [(a_RDR, ah_RDR), (b_RDR, bh_RDR)] $
409 HsApp (mk_easy_App map_RDR [tag2con_RDR tycon]) $
410 HsPar (enum_from_then_to_Expr
411 (mk_easy_App mkInt_RDR [ah_RDR])
412 (mk_easy_App mkInt_RDR [bh_RDR])
413 (HsVar (maxtag_RDR tycon)))
416 = mk_easy_FunMonoBind tycon_loc fromEnum_RDR [a_Pat] [] $
417 untag_Expr tycon [(a_RDR, ah_RDR)] $
418 (mk_easy_App mkInt_RDR [ah_RDR])
421 %************************************************************************
423 \subsubsection{Generating @Eval@ instance declarations}
425 %************************************************************************
428 gen_Eval_binds tycon = EmptyMonoBinds
431 %************************************************************************
433 \subsubsection{Generating @Bounded@ instance declarations}
435 %************************************************************************
438 gen_Bounded_binds tycon
439 = if isEnumerationTyCon tycon then
440 min_bound_enum `AndMonoBinds` max_bound_enum
442 ASSERT(length data_cons == 1)
443 min_bound_1con `AndMonoBinds` max_bound_1con
445 data_cons = tyConDataCons tycon
446 tycon_loc = getSrcLoc tycon
448 ----- enum-flavored: ---------------------------
449 min_bound_enum = mk_easy_FunMonoBind tycon_loc minBound_RDR [] [] (HsVar data_con_1_RDR)
450 max_bound_enum = mk_easy_FunMonoBind tycon_loc maxBound_RDR [] [] (HsVar data_con_N_RDR)
452 data_con_1 = head data_cons
453 data_con_N = last data_cons
454 data_con_1_RDR = qual_orig_name data_con_1
455 data_con_N_RDR = qual_orig_name data_con_N
457 ----- single-constructor-flavored: -------------
458 arity = dataConNumFields data_con_1
460 min_bound_1con = mk_easy_FunMonoBind tycon_loc minBound_RDR [] [] $
461 mk_easy_App data_con_1_RDR (nOfThem arity minBound_RDR)
462 max_bound_1con = mk_easy_FunMonoBind tycon_loc maxBound_RDR [] [] $
463 mk_easy_App data_con_1_RDR (nOfThem arity maxBound_RDR)
466 %************************************************************************
468 \subsubsection{Generating @Ix@ instance declarations}
470 %************************************************************************
472 Deriving @Ix@ is only possible for enumeration types and
473 single-constructor types. We deal with them in turn.
475 For an enumeration type, e.g.,
477 data Foo ... = N1 | N2 | ... | Nn
479 things go not too differently from @Enum@:
481 instance ... Ix (Foo ...) where
483 = map tag2con_Foo [con2tag_Foo a .. con2tag_Foo b]
487 = case (con2tag_Foo a) of { a# ->
488 case (con2tag_Foo b) of { b# ->
489 map tag2con_Foo (enumFromTo (I# a#) (I# b#))
494 then case (con2tag_Foo d -# con2tag_Foo a) of
496 else error "Ix.Foo.index: out of range"
500 p_tag = con2tag_Foo c
502 p_tag >= con2tag_Foo a && p_tag <= con2tag_Foo b
506 = case (con2tag_Foo a) of { a_tag ->
507 case (con2tag_Foo b) of { b_tag ->
508 case (con2tag_Foo c) of { c_tag ->
509 if (c_tag >=# a_tag) then
515 (modulo suitable case-ification to handle the unboxed tags)
517 For a single-constructor type (NB: this includes all tuples), e.g.,
519 data Foo ... = MkFoo a b Int Double c c
521 we follow the scheme given in Figure~19 of the Haskell~1.2 report
525 gen_Ix_binds :: TyCon -> RdrNameMonoBinds
528 = if isEnumerationTyCon tycon
532 tycon_str = getOccString tycon
533 tycon_loc = getSrcLoc tycon
535 --------------------------------------------------------------
536 enum_ixes = enum_range `AndMonoBinds`
537 enum_index `AndMonoBinds` enum_inRange
540 = mk_easy_FunMonoBind tycon_loc range_RDR [TuplePatIn [a_Pat, b_Pat]] [] $
541 untag_Expr tycon [(a_RDR, ah_RDR)] $
542 untag_Expr tycon [(b_RDR, bh_RDR)] $
543 HsApp (mk_easy_App map_RDR [tag2con_RDR tycon]) $
544 HsPar (enum_from_to_Expr
545 (mk_easy_App mkInt_RDR [ah_RDR])
546 (mk_easy_App mkInt_RDR [bh_RDR]))
549 = mk_easy_FunMonoBind tycon_loc index_RDR [AsPatIn c_RDR (TuplePatIn [a_Pat, b_Pat]), d_Pat] [] (
550 HsIf (HsPar (mk_easy_App inRange_RDR [c_RDR, d_RDR])) (
551 untag_Expr tycon [(a_RDR, ah_RDR)] (
552 untag_Expr tycon [(d_RDR, dh_RDR)] (
554 grhs = [OtherwiseGRHS (mk_easy_App mkInt_RDR [c_RDR]) tycon_loc]
557 (genOpApp (HsVar dh_RDR) minusH_RDR (HsVar ah_RDR))
558 [PatMatch (VarPatIn c_RDR)
559 (GRHSMatch (GRHSsAndBindsIn grhs EmptyBinds))]
563 HsApp (HsVar error_RDR) (HsLit (HsString (_PK_ ("Ix."++tycon_str++".index: out of range\n"))))
568 = mk_easy_FunMonoBind tycon_loc inRange_RDR [TuplePatIn [a_Pat, b_Pat], c_Pat] [] (
569 untag_Expr tycon [(a_RDR, ah_RDR)] (
570 untag_Expr tycon [(b_RDR, bh_RDR)] (
571 untag_Expr tycon [(c_RDR, ch_RDR)] (
572 HsIf (genOpApp (HsVar ch_RDR) geH_RDR (HsVar ah_RDR)) (
573 (genOpApp (HsVar ch_RDR) leH_RDR (HsVar bh_RDR))
578 --------------------------------------------------------------
579 single_con_ixes = single_con_range `AndMonoBinds`
580 single_con_index `AndMonoBinds` single_con_inRange
583 = case maybeTyConSingleCon tycon of -- just checking...
584 Nothing -> panic "get_Ix_binds"
585 Just dc -> if (any isPrimType (dataConRawArgTys dc)) then
586 error ("ERROR: Can't derive Ix for a single-constructor type with primitive argument types: "++tycon_str)
590 con_arity = dataConNumFields data_con
591 data_con_RDR = qual_orig_name data_con
592 con_pat xs = ConPatIn data_con_RDR (map VarPatIn xs)
593 con_expr xs = mk_easy_App data_con_RDR xs
595 as_needed = take con_arity as_RDRs
596 bs_needed = take con_arity bs_RDRs
597 cs_needed = take con_arity cs_RDRs
599 --------------------------------------------------------------
601 = mk_easy_FunMonoBind tycon_loc range_RDR [TuplePatIn [con_pat as_needed, con_pat bs_needed]] [] $
602 HsDo ListComp stmts tycon_loc
604 stmts = zipWith3Equal "single_con_range" mk_qual as_needed bs_needed cs_needed
606 [ReturnStmt (con_expr cs_needed)]
608 mk_qual a b c = BindStmt (VarPatIn c)
609 (HsApp (HsVar range_RDR) (ExplicitTuple [HsVar a, HsVar b]))
614 = mk_easy_FunMonoBind tycon_loc index_RDR [TuplePatIn [con_pat as_needed, con_pat bs_needed], con_pat cs_needed] [range_size] (
615 foldl mk_index (HsLit (HsInt 0)) (zip3 as_needed bs_needed cs_needed))
617 mk_index multiply_by (l, u, i)
619 (HsApp (HsApp (HsVar index_RDR) (ExplicitTuple [HsVar l, HsVar u])) (HsVar i))
622 (HsApp (HsVar rangeSize_RDR) (ExplicitTuple [HsVar l, HsVar u]))
623 ) times_RDR multiply_by
627 = mk_easy_FunMonoBind tycon_loc rangeSize_RDR [TuplePatIn [a_Pat, b_Pat]] [] (
629 (HsApp (HsApp (HsVar index_RDR) (ExplicitTuple [a_Expr, b_Expr])) b_Expr)
630 ) plus_RDR (HsLit (HsInt 1)))
634 = mk_easy_FunMonoBind tycon_loc inRange_RDR
635 [TuplePatIn [con_pat as_needed, con_pat bs_needed], con_pat cs_needed]
637 foldl1 and_Expr (zipWith3Equal "single_con_inRange" in_range as_needed bs_needed cs_needed))
639 in_range a b c = HsApp (HsApp (HsVar inRange_RDR) (ExplicitTuple [HsVar a, HsVar b])) (HsVar c)
642 %************************************************************************
644 \subsubsection{Generating @Read@ instance declarations}
646 %************************************************************************
648 Ignoring all the infix-ery mumbo jumbo (ToDo)
651 gen_Read_binds :: TyCon -> RdrNameMonoBinds
654 = reads_prec `AndMonoBinds` read_list
656 tycon_loc = getSrcLoc tycon
657 -----------------------------------------------------------------------
658 read_list = mk_easy_FunMonoBind tycon_loc readList_RDR [] []
659 (HsApp (HsVar readList___RDR) (HsPar (HsApp (HsVar readsPrec_RDR) (HsLit (HsInt 0)))))
660 -----------------------------------------------------------------------
663 read_con_comprehensions
664 = map read_con (tyConDataCons tycon)
666 mk_easy_FunMonoBind tycon_loc readsPrec_RDR [a_Pat, b_Pat] [] (
667 foldr1 append_Expr read_con_comprehensions
670 read_con data_con -- note: "b" is the string being "read"
672 data_con_RDR = qual_orig_name data_con
673 data_con_str= occNameString (getOccName data_con)
674 con_arity = dataConNumFields data_con
675 as_needed = take con_arity as_RDRs
676 bs_needed = take con_arity bs_RDRs
677 con_expr = mk_easy_App data_con_RDR as_needed
678 nullary_con = isNullaryDataCon data_con
682 (TuplePatIn [LitPatIn (HsString data_con_str), d_Pat])
683 (HsApp (HsVar lex_RDR) c_Expr)
686 field_quals = snd (mapAccumL mk_qual d_Expr (zipEqual "as_needed" as_needed bs_needed))
687 mk_qual draw_from (con_field, str_left)
688 = (HsVar str_left, -- what to draw from down the line...
690 (TuplePatIn [VarPatIn con_field, VarPatIn str_left])
691 (HsApp (HsApp (HsVar readsPrec_RDR) (HsLit (HsInt 10))) draw_from)
695 result_expr = ExplicitTuple [con_expr, if null bs_needed
697 else HsVar (last bs_needed)]
699 stmts = (con_qual : field_quals) ++ [ReturnStmt result_expr]
703 = if nullary_con then -- must be False (parens are surely optional)
705 else -- parens depend on precedence...
706 HsPar (genOpApp a_Expr gt_RDR (HsLit (HsInt 9)))
709 readParen_Expr read_paren_arg $ HsPar $
710 HsLam (mk_easy_Match tycon_loc [c_Pat] [] $
711 HsDo ListComp stmts tycon_loc)
715 %************************************************************************
717 \subsubsection{Generating @Show@ instance declarations}
719 %************************************************************************
721 Ignoring all the infix-ery mumbo jumbo (ToDo)
724 gen_Show_binds :: TyCon -> RdrNameMonoBinds
727 = shows_prec `AndMonoBinds` show_list
729 tycon_loc = getSrcLoc tycon
730 -----------------------------------------------------------------------
731 show_list = mk_easy_FunMonoBind tycon_loc showList_RDR [] []
732 (HsApp (HsVar showList___RDR) (HsPar (HsApp (HsVar showsPrec_RDR) (HsLit (HsInt 0)))))
733 -----------------------------------------------------------------------
735 = mk_FunMonoBind tycon_loc showsPrec_RDR (map pats_etc (tyConDataCons tycon))
739 data_con_RDR = qual_orig_name data_con
740 con_arity = dataConNumFields data_con
741 bs_needed = take con_arity bs_RDRs
742 con_pat = ConPatIn data_con_RDR (map VarPatIn bs_needed)
743 nullary_con = isNullaryDataCon data_con
746 = let nm = occNameString (getOccName data_con)
747 space_maybe = if nullary_con then _NIL_ else SLIT(" ")
749 HsApp (HsVar showString_RDR) (HsLit (HsString (nm _APPEND_ space_maybe)))
751 show_thingies = show_con : (spacified real_show_thingies)
754 = [ HsApp (HsApp (HsVar showsPrec_RDR) (HsLit (HsInt 10))) (HsVar b)
757 if nullary_con then -- skip the showParen junk...
758 ASSERT(null bs_needed)
759 ([a_Pat, con_pat], show_con)
762 showParen_Expr (HsPar (genOpApp a_Expr ge_RDR (HsLit (HsInt 10))))
763 (HsPar (nested_compose_Expr show_thingies)))
767 spacified (x:xs) = (x : (HsVar showSpace_RDR) : spacified xs)
770 %************************************************************************
772 \subsection{Generating extra binds (@con2tag@ and @tag2con@)}
774 %************************************************************************
779 con2tag_Foo :: Foo ... -> Int#
780 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
781 maxtag_Foo :: Int -- ditto (NB: not unboxed)
784 The `tags' here start at zero, hence the @fIRST_TAG@ (currently one)
789 = GenCon2Tag | GenTag2Con | GenMaxTag
791 gen_tag_n_con_monobind
792 :: (RdrName, -- (proto)Name for the thing in question
793 TyCon, -- tycon in question
797 gen_tag_n_con_monobind (rdr_name, tycon, GenCon2Tag)
798 = mk_FunMonoBind (getSrcLoc tycon) rdr_name (map mk_stuff (tyConDataCons tycon))
800 mk_stuff :: DataCon -> ([RdrNamePat], RdrNameHsExpr)
803 = ASSERT(isDataCon var)
804 ([pat], HsLit (HsIntPrim (toInteger ((dataConTag var) - fIRST_TAG))))
806 pat = ConPatIn var_RDR (nOfThem (dataConNumFields var) WildPatIn)
807 var_RDR = qual_orig_name var
809 gen_tag_n_con_monobind (rdr_name, tycon, GenTag2Con)
810 = mk_FunMonoBind (getSrcLoc tycon) rdr_name (map mk_stuff (tyConDataCons tycon) ++
811 [([WildPatIn], impossible_Expr)])
813 mk_stuff :: DataCon -> ([RdrNamePat], RdrNameHsExpr)
816 = ASSERT(isDataCon var)
817 ([lit_pat], HsVar var_RDR)
819 lit_pat = ConPatIn mkInt_RDR [LitPatIn (HsIntPrim (toInteger ((dataConTag var) - fIRST_TAG)))]
820 var_RDR = qual_orig_name var
822 gen_tag_n_con_monobind (rdr_name, tycon, GenMaxTag)
823 = mk_easy_FunMonoBind (getSrcLoc tycon)
824 rdr_name [] [] (HsApp (HsVar mkInt_RDR) (HsLit (HsIntPrim max_tag)))
826 max_tag = case (tyConDataCons tycon) of
827 data_cons -> toInteger ((length data_cons) - fIRST_TAG)
831 %************************************************************************
833 \subsection{Utility bits for generating bindings}
835 %************************************************************************
837 @mk_easy_FunMonoBind fun pats binds expr@ generates:
839 fun pat1 pat2 ... patN = expr where binds
842 @mk_FunMonoBind fun [([p1a, p1b, ...], e1), ...]@ is for
843 multi-clause definitions; it generates:
845 fun p1a p1b ... p1N = e1
846 fun p2a p2b ... p2N = e2
848 fun pMa pMb ... pMN = eM
852 mk_easy_FunMonoBind :: SrcLoc -> RdrName -> [RdrNamePat]
853 -> [RdrNameMonoBinds] -> RdrNameHsExpr
856 mk_easy_FunMonoBind loc fun pats binds expr
857 = FunMonoBind fun False{-not infix-} [mk_easy_Match loc pats binds expr] loc
859 mk_easy_Match loc pats binds expr
860 = mk_match loc pats expr (mkbind binds)
862 mkbind [] = EmptyBinds
863 mkbind bs = SingleBind (RecBind (foldr1 AndMonoBinds bs))
864 -- The renamer expects everything in its input to be a
865 -- "recursive" MonoBinds, and it is its job to sort things out
868 mk_FunMonoBind :: SrcLoc -> RdrName
869 -> [([RdrNamePat], RdrNameHsExpr)]
872 mk_FunMonoBind loc fun [] = panic "TcGenDeriv:mk_FunMonoBind"
873 mk_FunMonoBind loc fun pats_and_exprs
874 = FunMonoBind fun False{-not infix-}
875 [ mk_match loc p e EmptyBinds | (p,e) <-pats_and_exprs ]
878 mk_match loc pats expr binds
880 (GRHSMatch (GRHSsAndBindsIn [OtherwiseGRHS expr loc] binds))
883 paren p@(VarPatIn _) = p
884 paren other_p = ParPatIn other_p
888 mk_easy_App f xs = foldl HsApp (HsVar f) (map HsVar xs)
891 ToDo: Better SrcLocs.
894 compare_Case, cmp_eq_Expr ::
895 RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
896 -> RdrNameHsExpr -> RdrNameHsExpr
900 -> RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
901 -> RdrNameHsExpr -> RdrNameHsExpr
903 careful_compare_Case :: -- checks for primitive types...
905 -> RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
906 -> RdrNameHsExpr -> RdrNameHsExpr
909 compare_Case = compare_gen_Case compare_RDR
910 cmp_eq_Expr = compare_gen_Case cmp_eq_RDR
912 compare_gen_Case fun lt eq gt a b
913 = HsCase (HsPar (HsApp (HsApp (HsVar fun) a) b)) {-of-}
914 [PatMatch (ConPatIn ltTag_RDR [])
915 (GRHSMatch (GRHSsAndBindsIn [OtherwiseGRHS lt mkGeneratedSrcLoc] EmptyBinds)),
917 PatMatch (ConPatIn eqTag_RDR [])
918 (GRHSMatch (GRHSsAndBindsIn [OtherwiseGRHS eq mkGeneratedSrcLoc] EmptyBinds)),
920 PatMatch (ConPatIn gtTag_RDR [])
921 (GRHSMatch (GRHSsAndBindsIn [OtherwiseGRHS gt mkGeneratedSrcLoc] EmptyBinds))]
924 careful_compare_Case ty lt eq gt a b
925 = if not (isPrimType ty) then
926 compare_gen_Case compare_RDR lt eq gt a b
928 else -- we have to do something special for primitive things...
929 HsIf (genOpApp a relevant_eq_op b)
931 (HsIf (genOpApp a relevant_lt_op b) lt gt mkGeneratedSrcLoc)
934 relevant_eq_op = assoc_ty_id eq_op_tbl ty
935 relevant_lt_op = assoc_ty_id lt_op_tbl ty
938 = if null res then panic "assoc_ty"
941 res = [id | (ty',id) <- tyids, eqTy ty ty']
944 [(charPrimTy, eqH_Char_RDR)
945 ,(intPrimTy, eqH_Int_RDR)
946 ,(wordPrimTy, eqH_Word_RDR)
947 ,(addrPrimTy, eqH_Addr_RDR)
948 ,(floatPrimTy, eqH_Float_RDR)
949 ,(doublePrimTy, eqH_Double_RDR)
953 [(charPrimTy, ltH_Char_RDR)
954 ,(intPrimTy, ltH_Int_RDR)
955 ,(wordPrimTy, ltH_Word_RDR)
956 ,(addrPrimTy, ltH_Addr_RDR)
957 ,(floatPrimTy, ltH_Float_RDR)
958 ,(doublePrimTy, ltH_Double_RDR)
961 -----------------------------------------------------------------------
963 and_Expr, append_Expr :: RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
965 and_Expr a b = genOpApp a and_RDR b
966 append_Expr a b = genOpApp a append_RDR b
968 -----------------------------------------------------------------------
970 eq_Expr :: Type -> RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
972 = if not (isPrimType ty) then
974 else -- we have to do something special for primitive things...
975 genOpApp a relevant_eq_op b
977 relevant_eq_op = assoc_ty_id eq_op_tbl ty
981 untag_Expr :: TyCon -> [(RdrName, RdrName)] -> RdrNameHsExpr -> RdrNameHsExpr
982 untag_Expr tycon [] expr = expr
983 untag_Expr tycon ((untag_this, put_tag_here) : more) expr
984 = HsCase (HsPar (HsApp (con2tag_Expr tycon) (HsVar untag_this))) {-of-}
985 [PatMatch (VarPatIn put_tag_here)
986 (GRHSMatch (GRHSsAndBindsIn grhs EmptyBinds))]
989 grhs = [OtherwiseGRHS (untag_Expr tycon more expr) mkGeneratedSrcLoc]
991 cmp_tags_Expr :: RdrName -- Comparison op
992 -> RdrName -> RdrName -- Things to compare
993 -> RdrNameHsExpr -- What to return if true
994 -> RdrNameHsExpr -- What to return if false
997 cmp_tags_Expr op a b true_case false_case
998 = HsIf (genOpApp (HsVar a) op (HsVar b)) true_case false_case mkGeneratedSrcLoc
1001 :: RdrNameHsExpr -> RdrNameHsExpr
1003 enum_from_then_to_Expr
1004 :: RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr
1007 enum_from_to_Expr f t2 = HsApp (HsApp (HsVar enumFromTo_RDR) f) t2
1008 enum_from_then_to_Expr f t t2 = HsApp (HsApp (HsApp (HsVar enumFromThenTo_RDR) f) t) t2
1010 showParen_Expr, readParen_Expr
1011 :: RdrNameHsExpr -> RdrNameHsExpr
1014 showParen_Expr e1 e2 = HsApp (HsApp (HsVar showParen_RDR) e1) e2
1015 readParen_Expr e1 e2 = HsApp (HsApp (HsVar readParen_RDR) e1) e2
1017 nested_compose_Expr :: [RdrNameHsExpr] -> RdrNameHsExpr
1019 nested_compose_Expr [e] = parenify e
1020 nested_compose_Expr (e:es)
1021 = HsApp (HsApp (HsVar compose_RDR) (parenify e)) (nested_compose_Expr es)
1023 -- impossible_Expr is used in case RHSs that should never happen.
1024 -- We generate these to keep the desugarer from complaining that they *might* happen!
1025 impossible_Expr = HsApp (HsVar error_RDR) (HsLit (HsString (_PK_ "Urk! in TcGenDeriv")))
1027 parenify e@(HsVar _) = e
1028 parenify e = HsPar e
1030 -- genOpApp wraps brackets round the operator application, so that the
1031 -- renamer won't subsequently try to re-associate it.
1032 -- For some reason the renamer doesn't reassociate it right, and I can't
1033 -- be bothered to find out why just now.
1035 genOpApp e1 op e2 = mkOpApp e1 op e2
1039 qual_orig_name n = case modAndOcc n of { (m,n) -> Qual m n }
1041 a_RDR = varUnqual SLIT("a")
1042 b_RDR = varUnqual SLIT("b")
1043 c_RDR = varUnqual SLIT("c")
1044 d_RDR = varUnqual SLIT("d")
1045 ah_RDR = varUnqual SLIT("a#")
1046 bh_RDR = varUnqual SLIT("b#")
1047 ch_RDR = varUnqual SLIT("c#")
1048 dh_RDR = varUnqual SLIT("d#")
1049 cmp_eq_RDR = varUnqual SLIT("cmp_eq")
1050 rangeSize_RDR = varUnqual SLIT("rangeSize")
1052 as_RDRs = [ varUnqual (_PK_ ("a"++show i)) | i <- [(1::Int) .. ] ]
1053 bs_RDRs = [ varUnqual (_PK_ ("b"++show i)) | i <- [(1::Int) .. ] ]
1054 cs_RDRs = [ varUnqual (_PK_ ("c"++show i)) | i <- [(1::Int) .. ] ]
1056 a_Expr = HsVar a_RDR
1057 b_Expr = HsVar b_RDR
1058 c_Expr = HsVar c_RDR
1059 d_Expr = HsVar d_RDR
1060 ltTag_Expr = HsVar ltTag_RDR
1061 eqTag_Expr = HsVar eqTag_RDR
1062 gtTag_Expr = HsVar gtTag_RDR
1063 false_Expr = HsVar false_RDR
1064 true_Expr = HsVar true_RDR
1066 con2tag_Expr tycon = HsVar (con2tag_RDR tycon)
1068 a_Pat = VarPatIn a_RDR
1069 b_Pat = VarPatIn b_RDR
1070 c_Pat = VarPatIn c_RDR
1071 d_Pat = VarPatIn d_RDR
1073 con2tag_RDR, tag2con_RDR, maxtag_RDR :: TyCon -> RdrName
1075 con2tag_RDR tycon = varUnqual (SLIT("con2tag_") _APPEND_ occNameString (getOccName tycon) _APPEND_ SLIT("#"))
1076 tag2con_RDR tycon = varUnqual (SLIT("tag2con_") _APPEND_ occNameString (getOccName tycon) _APPEND_ SLIT("#"))
1077 maxtag_RDR tycon = varUnqual (SLIT("maxtag_") _APPEND_ occNameString (getOccName tycon) _APPEND_ SLIT("#"))