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