24579df162331ba216c797b4ca7161d4be379f27
[ghc-hetmet.git] / compiler / deSugar / DsUtils.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Utilities for desugaring
7
8 This module exports some utility functions of no great interest.
9
10 \begin{code}
11
12 -- | Utility functions for constructing Core syntax, principally for desugaring
13 module DsUtils (
14         EquationInfo(..), 
15         firstPat, shiftEqns,
16
17         MatchResult(..), CanItFail(..), 
18         cantFailMatchResult, alwaysFailMatchResult,
19         extractMatchResult, combineMatchResults, 
20         adjustMatchResult,  adjustMatchResultDs,
21         mkCoLetMatchResult, mkViewMatchResult, mkGuardedMatchResult, 
22         matchCanFail, mkEvalMatchResult,
23         mkCoPrimCaseMatchResult, mkCoAlgCaseMatchResult,
24         wrapBind, wrapBinds,
25
26         mkErrorAppDs,
27
28         seqVar,
29
30         -- LHs tuples
31         mkLHsVarTup, mkLHsTup, mkLHsVarPatTup, mkLHsPatTup,
32         mkBigLHsVarTup, mkBigLHsTup, mkBigLHsVarPatTup, mkBigLHsPatTup,
33
34         mkSelectorBinds,
35
36         dsSyntaxTable, lookupEvidence,
37
38         selectSimpleMatchVarL, selectMatchVars, selectMatchVar,
39         mkTickBox, mkOptTickBox, mkBinaryTickBox
40     ) where
41
42 #include "HsVersions.h"
43
44 import {-# SOURCE #-}   Match ( matchSimply )
45 import {-# SOURCE #-}   DsExpr( dsExpr )
46
47 import HsSyn
48 import TcHsSyn
49 import TcType( tcSplitTyConApp )
50 import CoreSyn
51 import DsMonad
52
53 import CoreUtils
54 import MkCore
55 import MkId
56 import Id
57 import Var
58 import Name
59 import Literal
60 import TyCon
61 import DataCon
62 import Type
63 import Coercion
64 import TysPrim
65 import TysWiredIn
66 import BasicTypes
67 import UniqSet
68 import UniqSupply
69 import PrelNames
70 import Outputable
71 import SrcLoc
72 import Util
73 import ListSetOps
74 import FastString
75 import StaticFlags
76
77 import Data.Char
78 \end{code}
79
80
81
82 %************************************************************************
83 %*                                                                      *
84                 Rebindable syntax
85 %*                                                                      *
86 %************************************************************************
87
88 \begin{code}
89 dsSyntaxTable :: SyntaxTable Id 
90                -> DsM ([CoreBind],      -- Auxiliary bindings
91                        [(Name,Id)])     -- Maps the standard name to its value
92
93 dsSyntaxTable rebound_ids = do
94     (binds_s, prs) <- mapAndUnzipM mk_bind rebound_ids
95     return (concat binds_s, prs)
96   where
97         -- The cheapo special case can happen when we 
98         -- make an intermediate HsDo when desugaring a RecStmt
99     mk_bind (std_name, HsVar id) = return ([], (std_name, id))
100     mk_bind (std_name, expr) = do
101            rhs <- dsExpr expr
102            id <- newSysLocalDs (exprType rhs)
103            return ([NonRec id rhs], (std_name, id))
104
105 lookupEvidence :: [(Name, Id)] -> Name -> Id
106 lookupEvidence prs std_name
107   = assocDefault (mk_panic std_name) prs std_name
108   where
109     mk_panic std_name = pprPanic "dsSyntaxTable" (ptext (sLit "Not found:") <+> ppr std_name)
110 \end{code}
111
112 %************************************************************************
113 %*                                                                      *
114 \subsection{ Selecting match variables}
115 %*                                                                      *
116 %************************************************************************
117
118 We're about to match against some patterns.  We want to make some
119 @Ids@ to use as match variables.  If a pattern has an @Id@ readily at
120 hand, which should indeed be bound to the pattern as a whole, then use it;
121 otherwise, make one up.
122
123 \begin{code}
124 selectSimpleMatchVarL :: LPat Id -> DsM Id
125 selectSimpleMatchVarL pat = selectMatchVar (unLoc pat)
126
127 -- (selectMatchVars ps tys) chooses variables of type tys
128 -- to use for matching ps against.  If the pattern is a variable,
129 -- we try to use that, to save inventing lots of fresh variables.
130 --
131 -- OLD, but interesting note:
132 --    But even if it is a variable, its type might not match.  Consider
133 --      data T a where
134 --        T1 :: Int -> T Int
135 --        T2 :: a   -> T a
136 --
137 --      f :: T a -> a -> Int
138 --      f (T1 i) (x::Int) = x
139 --      f (T2 i) (y::a)   = 0
140 --    Then we must not choose (x::Int) as the matching variable!
141 -- And nowadays we won't, because the (x::Int) will be wrapped in a CoPat
142
143 selectMatchVars :: [Pat Id] -> DsM [Id]
144 selectMatchVars ps = mapM selectMatchVar ps
145
146 selectMatchVar :: Pat Id -> DsM Id
147 selectMatchVar (BangPat pat)   = selectMatchVar (unLoc pat)
148 selectMatchVar (LazyPat pat)   = selectMatchVar (unLoc pat)
149 selectMatchVar (ParPat pat)    = selectMatchVar (unLoc pat)
150 selectMatchVar (VarPat var)    = return var
151 selectMatchVar (AsPat var _) = return (unLoc var)
152 selectMatchVar other_pat       = newSysLocalDs (hsPatType other_pat)
153                                   -- OK, better make up one...
154 \end{code}
155
156
157 %************************************************************************
158 %*                                                                      *
159 %* type synonym EquationInfo and access functions for its pieces        *
160 %*                                                                      *
161 %************************************************************************
162 \subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
163
164 The ``equation info'' used by @match@ is relatively complicated and
165 worthy of a type synonym and a few handy functions.
166
167 \begin{code}
168 firstPat :: EquationInfo -> Pat Id
169 firstPat eqn = ASSERT( notNull (eqn_pats eqn) ) head (eqn_pats eqn)
170
171 shiftEqns :: [EquationInfo] -> [EquationInfo]
172 -- Drop the first pattern in each equation
173 shiftEqns eqns = [ eqn { eqn_pats = tail (eqn_pats eqn) } | eqn <- eqns ]
174 \end{code}
175
176 Functions on MatchResults
177
178 \begin{code}
179 matchCanFail :: MatchResult -> Bool
180 matchCanFail (MatchResult CanFail _)  = True
181 matchCanFail (MatchResult CantFail _) = False
182
183 alwaysFailMatchResult :: MatchResult
184 alwaysFailMatchResult = MatchResult CanFail (\fail -> return fail)
185
186 cantFailMatchResult :: CoreExpr -> MatchResult
187 cantFailMatchResult expr = MatchResult CantFail (\_ -> return expr)
188
189 extractMatchResult :: MatchResult -> CoreExpr -> DsM CoreExpr
190 extractMatchResult (MatchResult CantFail match_fn) _
191   = match_fn (error "It can't fail!")
192
193 extractMatchResult (MatchResult CanFail match_fn) fail_expr = do
194     (fail_bind, if_it_fails) <- mkFailurePair fail_expr
195     body <- match_fn if_it_fails
196     return (mkCoreLet fail_bind body)
197
198
199 combineMatchResults :: MatchResult -> MatchResult -> MatchResult
200 combineMatchResults (MatchResult CanFail      body_fn1)
201                     (MatchResult can_it_fail2 body_fn2)
202   = MatchResult can_it_fail2 body_fn
203   where
204     body_fn fail = do body2 <- body_fn2 fail
205                       (fail_bind, duplicatable_expr) <- mkFailurePair body2
206                       body1 <- body_fn1 duplicatable_expr
207                       return (Let fail_bind body1)
208
209 combineMatchResults match_result1@(MatchResult CantFail _) _
210   = match_result1
211
212 adjustMatchResult :: DsWrapper -> MatchResult -> MatchResult
213 adjustMatchResult encl_fn (MatchResult can_it_fail body_fn)
214   = MatchResult can_it_fail (\fail -> encl_fn <$> body_fn fail)
215
216 adjustMatchResultDs :: (CoreExpr -> DsM CoreExpr) -> MatchResult -> MatchResult
217 adjustMatchResultDs encl_fn (MatchResult can_it_fail body_fn)
218   = MatchResult can_it_fail (\fail -> encl_fn =<< body_fn fail)
219
220 wrapBinds :: [(Var,Var)] -> CoreExpr -> CoreExpr
221 wrapBinds [] e = e
222 wrapBinds ((new,old):prs) e = wrapBind new old (wrapBinds prs e)
223
224 wrapBind :: Var -> Var -> CoreExpr -> CoreExpr
225 wrapBind new old body   -- Can deal with term variables *or* type variables
226   | new==old    = body
227   | isTyVar new = Let (mkTyBind new (mkTyVarTy old)) body
228   | otherwise   = Let (NonRec new (Var old))         body
229
230 seqVar :: Var -> CoreExpr -> CoreExpr
231 seqVar var body = Case (Var var) var (exprType body)
232                         [(DEFAULT, [], body)]
233
234 mkCoLetMatchResult :: CoreBind -> MatchResult -> MatchResult
235 mkCoLetMatchResult bind = adjustMatchResult (mkCoreLet bind)
236
237 -- (mkViewMatchResult var' viewExpr var mr) makes the expression
238 -- let var' = viewExpr var in mr
239 mkViewMatchResult :: Id -> CoreExpr -> Id -> MatchResult -> MatchResult
240 mkViewMatchResult var' viewExpr var = 
241     adjustMatchResult (mkCoreLet (NonRec var' (mkCoreApp viewExpr (Var var))))
242
243 mkEvalMatchResult :: Id -> Type -> MatchResult -> MatchResult
244 mkEvalMatchResult var ty
245   = adjustMatchResult (\e -> Case (Var var) var ty [(DEFAULT, [], e)]) 
246
247 mkGuardedMatchResult :: CoreExpr -> MatchResult -> MatchResult
248 mkGuardedMatchResult pred_expr (MatchResult _ body_fn)
249   = MatchResult CanFail (\fail -> do body <- body_fn fail
250                                      return (mkIfThenElse pred_expr body fail))
251
252 mkCoPrimCaseMatchResult :: Id                           -- Scrutinee
253                     -> Type                             -- Type of the case
254                     -> [(Literal, MatchResult)]         -- Alternatives
255                     -> MatchResult
256 mkCoPrimCaseMatchResult var ty match_alts
257   = MatchResult CanFail mk_case
258   where
259     mk_case fail = do
260         alts <- mapM (mk_alt fail) sorted_alts
261         return (Case (Var var) var ty ((DEFAULT, [], fail) : alts))
262
263     sorted_alts = sortWith fst match_alts       -- Right order for a Case
264     mk_alt fail (lit, MatchResult _ body_fn) = do body <- body_fn fail
265                                                   return (LitAlt lit, [], body)
266
267
268 mkCoAlgCaseMatchResult :: Id                                    -- Scrutinee
269                     -> Type                                     -- Type of exp
270                     -> [(DataCon, [CoreBndr], MatchResult)]     -- Alternatives
271                     -> MatchResult
272 mkCoAlgCaseMatchResult var ty match_alts 
273   | isNewTyCon tycon            -- Newtype case; use a let
274   = ASSERT( null (tail match_alts) && null (tail arg_ids1) )
275     mkCoLetMatchResult (NonRec arg_id1 newtype_rhs) match_result1
276
277   | isPArrFakeAlts match_alts   -- Sugared parallel array; use a literal case 
278   = MatchResult CanFail mk_parrCase
279
280   | otherwise                   -- Datatype case; use a case
281   = MatchResult fail_flag mk_case
282   where
283     tycon = dataConTyCon con1
284         -- [Interesting: becuase of GADTs, we can't rely on the type of 
285         --  the scrutinised Id to be sufficiently refined to have a TyCon in it]
286
287         -- Stuff for newtype
288     (con1, arg_ids1, match_result1) = ASSERT( notNull match_alts ) head match_alts
289     arg_id1     = ASSERT( notNull arg_ids1 ) head arg_ids1
290     var_ty      = idType var
291     (tc, ty_args) = tcSplitTyConApp var_ty      -- Don't look through newtypes
292                                                 -- (not that splitTyConApp does, these days)
293     newtype_rhs = unwrapNewTypeBody tc ty_args (Var var)
294                 
295         -- Stuff for data types
296     data_cons      = tyConDataCons tycon
297     match_results  = [match_result | (_,_,match_result) <- match_alts]
298
299     fail_flag | exhaustive_case
300               = foldr1 orFail [can_it_fail | MatchResult can_it_fail _ <- match_results]
301               | otherwise
302               = CanFail
303
304     wild_var = mkWildId (idType var)
305     sorted_alts  = sortWith get_tag match_alts
306     get_tag (con, _, _) = dataConTag con
307     mk_case fail = do alts <- mapM (mk_alt fail) sorted_alts
308                       return (Case (Var var) wild_var ty (mk_default fail ++ alts))
309
310     mk_alt fail (con, args, MatchResult _ body_fn) = do
311           body <- body_fn fail
312           us <- newUniqueSupply
313           return (mkReboxingAlt (uniqsFromSupply us) con args body)
314
315     mk_default fail | exhaustive_case = []
316                     | otherwise       = [(DEFAULT, [], fail)]
317
318     un_mentioned_constructors
319         = mkUniqSet data_cons `minusUniqSet` mkUniqSet [ con | (con, _, _) <- match_alts]
320     exhaustive_case = isEmptyUniqSet un_mentioned_constructors
321
322         -- Stuff for parallel arrays
323         -- 
324         --  * the following is to desugar cases over fake constructors for
325         --   parallel arrays, which are introduced by `tidy1' in the `PArrPat'
326         --   case
327         --
328         -- Concerning `isPArrFakeAlts':
329         --
330         --  * it is *not* sufficient to just check the type of the type
331         --   constructor, as we have to be careful not to confuse the real
332         --   representation of parallel arrays with the fake constructors;
333         --   moreover, a list of alternatives must not mix fake and real
334         --   constructors (this is checked earlier on)
335         --
336         -- FIXME: We actually go through the whole list and make sure that
337         --        either all or none of the constructors are fake parallel
338         --        array constructors.  This is to spot equations that mix fake
339         --        constructors with the real representation defined in
340         --        `PrelPArr'.  It would be nicer to spot this situation
341         --        earlier and raise a proper error message, but it can really
342         --        only happen in `PrelPArr' anyway.
343         --
344     isPArrFakeAlts [(dcon, _, _)]      = isPArrFakeCon dcon
345     isPArrFakeAlts ((dcon, _, _):alts) = 
346       case (isPArrFakeCon dcon, isPArrFakeAlts alts) of
347         (True , True ) -> True
348         (False, False) -> False
349         _              -> panic "DsUtils: you may not mix `[:...:]' with `PArr' patterns"
350     isPArrFakeAlts [] = panic "DsUtils: unexpectedly found an empty list of PArr fake alternatives"
351     --
352     mk_parrCase fail = do
353       lengthP <- dsLookupGlobalId lengthPName
354       alt <- unboxAlt
355       return (Case (len lengthP) (mkWildId intTy) ty [alt])
356       where
357         elemTy      = case splitTyConApp (idType var) of
358                         (_, [elemTy]) -> elemTy
359                         _               -> panic panicMsg
360         panicMsg    = "DsUtils.mkCoAlgCaseMatchResult: not a parallel array?"
361         len lengthP = mkApps (Var lengthP) [Type elemTy, Var var]
362         --
363         unboxAlt = do
364           l      <- newSysLocalDs intPrimTy
365           indexP <- dsLookupGlobalId indexPName
366           alts   <- mapM (mkAlt indexP) sorted_alts
367           return (DataAlt intDataCon, [l], (Case (Var l) wild ty (dft : alts)))
368           where
369             wild = mkWildId intPrimTy
370             dft  = (DEFAULT, [], fail)
371         --
372         -- each alternative matches one array length (corresponding to one
373         -- fake array constructor), so the match is on a literal; each
374         -- alternative's body is extended by a local binding for each
375         -- constructor argument, which are bound to array elements starting
376         -- with the first
377         --
378         mkAlt indexP (con, args, MatchResult _ bodyFun) = do
379           body <- bodyFun fail
380           return (LitAlt lit, [], mkCoreLets binds body)
381           where
382             lit   = MachInt $ toInteger (dataConSourceArity con)
383             binds = [NonRec arg (indexExpr i) | (i, arg) <- zip [1..] args]
384             --
385             indexExpr i = mkApps (Var indexP) [Type elemTy, Var var, mkIntExpr i]
386 \end{code}
387
388 %************************************************************************
389 %*                                                                      *
390 \subsection{Desugarer's versions of some Core functions}
391 %*                                                                      *
392 %************************************************************************
393
394 \begin{code}
395 mkErrorAppDs :: Id              -- The error function
396              -> Type            -- Type to which it should be applied
397              -> String          -- The error message string to pass
398              -> DsM CoreExpr
399
400 mkErrorAppDs err_id ty msg = do
401     src_loc <- getSrcSpanDs
402     let
403         full_msg = showSDoc (hcat [ppr src_loc, text "|", text msg])
404         core_msg = Lit (mkMachString full_msg)
405         -- mkMachString returns a result of type String#
406     return (mkApps (Var err_id) [Type ty, core_msg])
407 \end{code}
408
409 %************************************************************************
410 %*                                                                      *
411 \subsection[mkSelectorBind]{Make a selector bind}
412 %*                                                                      *
413 %************************************************************************
414
415 This is used in various places to do with lazy patterns.
416 For each binder $b$ in the pattern, we create a binding:
417 \begin{verbatim}
418     b = case v of pat' -> b'
419 \end{verbatim}
420 where @pat'@ is @pat@ with each binder @b@ cloned into @b'@.
421
422 ToDo: making these bindings should really depend on whether there's
423 much work to be done per binding.  If the pattern is complex, it
424 should be de-mangled once, into a tuple (and then selected from).
425 Otherwise the demangling can be in-line in the bindings (as here).
426
427 Boring!  Boring!  One error message per binder.  The above ToDo is
428 even more helpful.  Something very similar happens for pattern-bound
429 expressions.
430
431 \begin{code}
432 mkSelectorBinds :: LPat Id      -- The pattern
433                 -> CoreExpr     -- Expression to which the pattern is bound
434                 -> DsM [(Id,CoreExpr)]
435
436 mkSelectorBinds (L _ (VarPat v)) val_expr
437   = return [(v, val_expr)]
438
439 mkSelectorBinds pat val_expr
440   | isSingleton binders || is_simple_lpat pat = do
441         -- Given   p = e, where p binds x,y
442         -- we are going to make
443         --      v = p   (where v is fresh)
444         --      x = case v of p -> x
445         --      y = case v of p -> x
446
447         -- Make up 'v'
448         -- NB: give it the type of *pattern* p, not the type of the *rhs* e.
449         -- This does not matter after desugaring, but there's a subtle 
450         -- issue with implicit parameters. Consider
451         --      (x,y) = ?i
452         -- Then, ?i is given type {?i :: Int}, a PredType, which is opaque
453         -- to the desugarer.  (Why opaque?  Because newtypes have to be.  Why
454         -- does it get that type?  So that when we abstract over it we get the
455         -- right top-level type  (?i::Int) => ...)
456         --
457         -- So to get the type of 'v', use the pattern not the rhs.  Often more
458         -- efficient too.
459       val_var <- newSysLocalDs (hsLPatType pat)
460
461         -- For the error message we make one error-app, to avoid duplication.
462         -- But we need it at different types... so we use coerce for that
463       err_expr <- mkErrorAppDs iRREFUT_PAT_ERROR_ID  unitTy (showSDoc (ppr pat))
464       err_var <- newSysLocalDs unitTy
465       binds <- mapM (mk_bind val_var err_var) binders
466       return ( (val_var, val_expr) : 
467                (err_var, err_expr) :
468                binds )
469
470
471   | otherwise = do
472       error_expr <- mkErrorAppDs iRREFUT_PAT_ERROR_ID   tuple_ty (showSDoc (ppr pat))
473       tuple_expr <- matchSimply val_expr PatBindRhs pat local_tuple error_expr
474       tuple_var <- newSysLocalDs tuple_ty
475       let
476           mk_tup_bind binder
477             = (binder, mkTupleSelector binders binder tuple_var (Var tuple_var))
478       return ( (tuple_var, tuple_expr) : map mk_tup_bind binders )
479   where
480     binders     = collectPatBinders pat
481     local_tuple = mkBigCoreVarTup binders
482     tuple_ty    = exprType local_tuple
483
484     mk_bind scrut_var err_var bndr_var = do
485     -- (mk_bind sv err_var) generates
486     --          bv = case sv of { pat -> bv; other -> coerce (type-of-bv) err_var }
487     -- Remember, pat binds bv
488         rhs_expr <- matchSimply (Var scrut_var) PatBindRhs pat
489                                 (Var bndr_var) error_expr
490         return (bndr_var, rhs_expr)
491       where
492         error_expr = mkCoerce co (Var err_var)
493         co         = mkUnsafeCoercion (exprType (Var err_var)) (idType bndr_var)
494
495     is_simple_lpat p = is_simple_pat (unLoc p)
496
497     is_simple_pat (TuplePat ps Boxed _)        = all is_triv_lpat ps
498     is_simple_pat (ConPatOut{ pat_args = ps }) = all is_triv_lpat (hsConPatArgs ps)
499     is_simple_pat (VarPat _)                   = True
500     is_simple_pat (ParPat p)                   = is_simple_lpat p
501     is_simple_pat _                                    = False
502
503     is_triv_lpat p = is_triv_pat (unLoc p)
504
505     is_triv_pat (VarPat _)  = True
506     is_triv_pat (WildPat _) = True
507     is_triv_pat (ParPat p)  = is_triv_lpat p
508     is_triv_pat _           = False
509
510 \end{code}
511
512 Creating tuples and their types for full Haskell expressions
513
514 \begin{code}
515
516 -- Smart constructors for source tuple expressions
517 mkLHsVarTup :: [Id] -> LHsExpr Id
518 mkLHsVarTup ids  = mkLHsTup (map nlHsVar ids)
519
520 mkLHsTup :: [LHsExpr Id] -> LHsExpr Id
521 mkLHsTup []     = nlHsVar unitDataConId
522 mkLHsTup [lexp] = lexp
523 mkLHsTup lexps  = L (getLoc (head lexps)) $ 
524                   ExplicitTuple lexps Boxed
525
526 -- Smart constructors for source tuple patterns
527 mkLHsVarPatTup :: [Id] -> LPat Id
528 mkLHsVarPatTup bs  = mkLHsPatTup (map nlVarPat bs)
529
530 mkLHsPatTup :: [LPat Id] -> LPat Id
531 mkLHsPatTup []     = noLoc $ mkVanillaTuplePat [] Boxed
532 mkLHsPatTup [lpat] = lpat
533 mkLHsPatTup lpats  = L (getLoc (head lpats)) $ 
534                      mkVanillaTuplePat lpats Boxed
535
536 -- The Big equivalents for the source tuple expressions
537 mkBigLHsVarTup :: [Id] -> LHsExpr Id
538 mkBigLHsVarTup ids = mkBigLHsTup (map nlHsVar ids)
539
540 mkBigLHsTup :: [LHsExpr Id] -> LHsExpr Id
541 mkBigLHsTup = mkChunkified mkLHsTup
542
543
544 -- The Big equivalents for the source tuple patterns
545 mkBigLHsVarPatTup :: [Id] -> LPat Id
546 mkBigLHsVarPatTup bs = mkBigLHsPatTup (map nlVarPat bs)
547
548 mkBigLHsPatTup :: [LPat Id] -> LPat Id
549 mkBigLHsPatTup = mkChunkified mkLHsPatTup
550 \end{code}
551
552 %************************************************************************
553 %*                                                                      *
554 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
555 %*                                                                      *
556 %************************************************************************
557
558 Generally, we handle pattern matching failure like this: let-bind a
559 fail-variable, and use that variable if the thing fails:
560 \begin{verbatim}
561         let fail.33 = error "Help"
562         in
563         case x of
564                 p1 -> ...
565                 p2 -> fail.33
566                 p3 -> fail.33
567                 p4 -> ...
568 \end{verbatim}
569 Then
570 \begin{itemize}
571 \item
572 If the case can't fail, then there'll be no mention of @fail.33@, and the
573 simplifier will later discard it.
574
575 \item
576 If it can fail in only one way, then the simplifier will inline it.
577
578 \item
579 Only if it is used more than once will the let-binding remain.
580 \end{itemize}
581
582 There's a problem when the result of the case expression is of
583 unboxed type.  Then the type of @fail.33@ is unboxed too, and
584 there is every chance that someone will change the let into a case:
585 \begin{verbatim}
586         case error "Help" of
587           fail.33 -> case ....
588 \end{verbatim}
589
590 which is of course utterly wrong.  Rather than drop the condition that
591 only boxed types can be let-bound, we just turn the fail into a function
592 for the primitive case:
593 \begin{verbatim}
594         let fail.33 :: Void -> Int#
595             fail.33 = \_ -> error "Help"
596         in
597         case x of
598                 p1 -> ...
599                 p2 -> fail.33 void
600                 p3 -> fail.33 void
601                 p4 -> ...
602 \end{verbatim}
603
604 Now @fail.33@ is a function, so it can be let-bound.
605
606 \begin{code}
607 mkFailurePair :: CoreExpr       -- Result type of the whole case expression
608               -> DsM (CoreBind, -- Binds the newly-created fail variable
609                                 -- to either the expression or \ _ -> expression
610                       CoreExpr) -- Either the fail variable, or fail variable
611                                 -- applied to unit tuple
612 mkFailurePair expr
613   | isUnLiftedType ty = do
614      fail_fun_var <- newFailLocalDs (unitTy `mkFunTy` ty)
615      fail_fun_arg <- newSysLocalDs unitTy
616      return (NonRec fail_fun_var (Lam fail_fun_arg expr),
617              App (Var fail_fun_var) (Var unitDataConId))
618
619   | otherwise = do
620      fail_var <- newFailLocalDs ty
621      return (NonRec fail_var expr, Var fail_var)
622   where
623     ty = exprType expr
624 \end{code}
625
626 \begin{code}
627 mkOptTickBox :: Maybe (Int,[Id]) -> CoreExpr -> DsM CoreExpr
628 mkOptTickBox Nothing e   = return e
629 mkOptTickBox (Just (ix,ids)) e = mkTickBox ix ids e
630
631 mkTickBox :: Int -> [Id] -> CoreExpr -> DsM CoreExpr
632 mkTickBox ix vars e = do
633        uq <- newUnique  
634        mod <- getModuleDs
635        let tick | opt_Hpc   = mkTickBoxOpId uq mod ix
636                 | otherwise = mkBreakPointOpId uq mod ix
637        uq2 <- newUnique         
638        let occName = mkVarOcc "tick"
639        let name = mkInternalName uq2 occName noSrcSpan   -- use mkSysLocal?
640        let var  = Id.mkLocalId name realWorldStatePrimTy
641        scrut <- 
642           if opt_Hpc 
643             then return (Var tick)
644             else do
645               let tickVar = Var tick
646               let tickType = mkFunTys (map idType vars) realWorldStatePrimTy 
647               let scrutApTy = App tickVar (Type tickType)
648               return (mkApps scrutApTy (map Var vars) :: Expr Id)
649        return $ Case scrut var ty [(DEFAULT,[],e)]
650   where
651      ty = exprType e
652
653 mkBinaryTickBox :: Int -> Int -> CoreExpr -> DsM CoreExpr
654 mkBinaryTickBox ixT ixF e = do
655        uq <- newUnique  
656        let bndr1 = mkSysLocal (fsLit "t1") uq boolTy 
657        falseBox <- mkTickBox ixF [] $ Var falseDataConId
658        trueBox  <- mkTickBox ixT [] $ Var trueDataConId
659        return $ Case e bndr1 boolTy
660                        [ (DataAlt falseDataCon, [], falseBox)
661                        , (DataAlt trueDataCon,  [], trueBox)
662                        ]
663 \end{code}