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