Fix Trac #3403: interaction of CPR and pattern-match failure
[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         mkLHsVarPatTup, mkLHsPatTup, mkVanillaTuplePat,
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 big tuples and their types for full Haskell expressions.
587 They work over *Ids*, and create tuples replete with their types,
588 which is whey they are not in HsUtils.
589
590 \begin{code}
591 mkLHsPatTup :: [LPat Id] -> LPat Id
592 mkLHsPatTup []     = noLoc $ mkVanillaTuplePat [] Boxed
593 mkLHsPatTup [lpat] = lpat
594 mkLHsPatTup lpats  = L (getLoc (head lpats)) $ 
595                      mkVanillaTuplePat lpats Boxed
596
597 mkLHsVarPatTup :: [Id] -> LPat Id
598 mkLHsVarPatTup bs  = mkLHsPatTup (map nlVarPat bs)
599
600 mkVanillaTuplePat :: [OutPat Id] -> Boxity -> Pat Id
601 -- A vanilla tuple pattern simply gets its type from its sub-patterns
602 mkVanillaTuplePat pats box 
603   = TuplePat pats box (mkTupleTy box (length pats) (map hsLPatType pats))
604
605 -- The Big equivalents for the source tuple expressions
606 mkBigLHsVarTup :: [Id] -> LHsExpr Id
607 mkBigLHsVarTup ids = mkBigLHsTup (map nlHsVar ids)
608
609 mkBigLHsTup :: [LHsExpr Id] -> LHsExpr Id
610 mkBigLHsTup = mkChunkified mkLHsTupleExpr
611
612 -- The Big equivalents for the source tuple patterns
613 mkBigLHsVarPatTup :: [Id] -> LPat Id
614 mkBigLHsVarPatTup bs = mkBigLHsPatTup (map nlVarPat bs)
615
616 mkBigLHsPatTup :: [LPat Id] -> LPat Id
617 mkBigLHsPatTup = mkChunkified mkLHsPatTup
618 \end{code}
619
620 %************************************************************************
621 %*                                                                      *
622 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
623 %*                                                                      *
624 %************************************************************************
625
626 Generally, we handle pattern matching failure like this: let-bind a
627 fail-variable, and use that variable if the thing fails:
628 \begin{verbatim}
629         let fail.33 = error "Help"
630         in
631         case x of
632                 p1 -> ...
633                 p2 -> fail.33
634                 p3 -> fail.33
635                 p4 -> ...
636 \end{verbatim}
637 Then
638 \begin{itemize}
639 \item
640 If the case can't fail, then there'll be no mention of @fail.33@, and the
641 simplifier will later discard it.
642
643 \item
644 If it can fail in only one way, then the simplifier will inline it.
645
646 \item
647 Only if it is used more than once will the let-binding remain.
648 \end{itemize}
649
650 There's a problem when the result of the case expression is of
651 unboxed type.  Then the type of @fail.33@ is unboxed too, and
652 there is every chance that someone will change the let into a case:
653 \begin{verbatim}
654         case error "Help" of
655           fail.33 -> case ....
656 \end{verbatim}
657
658 which is of course utterly wrong.  Rather than drop the condition that
659 only boxed types can be let-bound, we just turn the fail into a function
660 for the primitive case:
661 \begin{verbatim}
662         let fail.33 :: Void -> Int#
663             fail.33 = \_ -> error "Help"
664         in
665         case x of
666                 p1 -> ...
667                 p2 -> fail.33 void
668                 p3 -> fail.33 void
669                 p4 -> ...
670 \end{verbatim}
671
672 Now @fail.33@ is a function, so it can be let-bound.
673
674 \begin{code}
675 mkFailurePair :: CoreExpr       -- Result type of the whole case expression
676               -> DsM (CoreBind, -- Binds the newly-created fail variable
677                                 -- to \ _ -> expression
678                       CoreExpr) -- Fail variable applied to realWorld#
679 -- See Note [Failure thunks and CPR]
680 mkFailurePair expr
681   = do { fail_fun_var <- newFailLocalDs (realWorldStatePrimTy `mkFunTy` ty)
682        ; fail_fun_arg <- newSysLocalDs realWorldStatePrimTy
683        ; return (NonRec fail_fun_var (Lam fail_fun_arg expr),
684                  App (Var fail_fun_var) (Var realWorldPrimId)) }
685   where
686     ty = exprType expr
687 \end{code}
688
689 Note [Failure thunks and CPR]
690 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
691 When we make a failure point we ensure that it
692 does not look like a thunk. Example:
693
694    let fail = \rw -> error "urk"
695    in case x of 
696         [] -> fail realWorld#
697         (y:ys) -> case ys of
698                     [] -> fail realWorld#  
699                     (z:zs) -> (y,z)
700
701 Reason: we know that a failure point is always a "join point" and is
702 entered at most once.  Adding a dummy 'realWorld' token argument makes
703 it clear that sharing is not an issue.  And that in turn makes it more
704 CPR-friendly.  This matters a lot: if you don't get it right, you lose
705 the tail call property.  For example, see Trac #3403.
706
707 \begin{code}
708 mkOptTickBox :: Maybe (Int,[Id]) -> CoreExpr -> DsM CoreExpr
709 mkOptTickBox Nothing e   = return e
710 mkOptTickBox (Just (ix,ids)) e = mkTickBox ix ids e
711
712 mkTickBox :: Int -> [Id] -> CoreExpr -> DsM CoreExpr
713 mkTickBox ix vars e = do
714        uq <- newUnique  
715        mod <- getModuleDs
716        let tick | opt_Hpc   = mkTickBoxOpId uq mod ix
717                 | otherwise = mkBreakPointOpId uq mod ix
718        uq2 <- newUnique         
719        let occName = mkVarOcc "tick"
720        let name = mkInternalName uq2 occName noSrcSpan   -- use mkSysLocal?
721        let var  = Id.mkLocalId name realWorldStatePrimTy
722        scrut <- 
723           if opt_Hpc 
724             then return (Var tick)
725             else do
726               let tickVar = Var tick
727               let tickType = mkFunTys (map idType vars) realWorldStatePrimTy 
728               let scrutApTy = App tickVar (Type tickType)
729               return (mkApps scrutApTy (map Var vars) :: Expr Id)
730        return $ Case scrut var ty [(DEFAULT,[],e)]
731   where
732      ty = exprType e
733
734 mkBinaryTickBox :: Int -> Int -> CoreExpr -> DsM CoreExpr
735 mkBinaryTickBox ixT ixF e = do
736        uq <- newUnique  
737        let bndr1 = mkSysLocal (fsLit "t1") uq boolTy 
738        falseBox <- mkTickBox ixF [] $ Var falseDataConId
739        trueBox  <- mkTickBox ixT [] $ Var trueDataConId
740        return $ Case e bndr1 boolTy
741                        [ (DataAlt falseDataCon, [], falseBox)
742                        , (DataAlt trueDataCon,  [], trueBox)
743                        ]
744 \end{code}