Super-monster patch implementing the new typechecker -- at last
[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   | isTyCoVar 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 #2273
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, thus:
451    x  `seq` e2 ==> case x of x -> e2    -- Note shadowing!
452    e1 `seq` e2 ==> case x of _ -> e2
453
454 So we desugar our example to:
455    let chp = case b of { True -> fst x; False -> 0 }
456    case chp of chp { I# -> ...chp... }
457 And now all is well.
458
459 The reason it's a hack is because if you define mySeq=seq, the hack
460 won't work on mySeq.  
461
462 Note [Desugaring seq (3)] cf Trac #2409
463 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
464 The isLocalId ensures that we don't turn 
465         True `seq` e
466 into
467         case True of True { ... }
468 which stupidly tries to bind the datacon 'True'. 
469
470 \begin{code}
471 mkCoreAppDs  :: CoreExpr -> CoreExpr -> CoreExpr
472 mkCoreAppDs (Var f `App` Type ty1 `App` Type ty2 `App` arg1) arg2
473   | f `hasKey` seqIdKey            -- Note [Desugaring seq (1), (2)]
474   = Case arg1 case_bndr ty2 [(DEFAULT,[],arg2)]
475   where
476     case_bndr = case arg1 of
477                    Var v1 | isLocalId v1 -> v1        -- Note [Desugaring seq (2) and (3)]
478                    _                     -> mkWildValBinder ty1
479
480 mkCoreAppDs fun arg = mkCoreApp fun arg  -- The rest is done in MkCore
481
482 mkCoreAppsDs :: CoreExpr -> [CoreExpr] -> CoreExpr
483 mkCoreAppsDs fun args = foldl mkCoreAppDs fun args
484 \end{code}
485
486
487 %************************************************************************
488 %*                                                                      *
489 \subsection[mkSelectorBind]{Make a selector bind}
490 %*                                                                      *
491 %************************************************************************
492
493 This is used in various places to do with lazy patterns.
494 For each binder $b$ in the pattern, we create a binding:
495 \begin{verbatim}
496     b = case v of pat' -> b'
497 \end{verbatim}
498 where @pat'@ is @pat@ with each binder @b@ cloned into @b'@.
499
500 ToDo: making these bindings should really depend on whether there's
501 much work to be done per binding.  If the pattern is complex, it
502 should be de-mangled once, into a tuple (and then selected from).
503 Otherwise the demangling can be in-line in the bindings (as here).
504
505 Boring!  Boring!  One error message per binder.  The above ToDo is
506 even more helpful.  Something very similar happens for pattern-bound
507 expressions.
508
509 \begin{code}
510 mkSelectorBinds :: LPat Id      -- The pattern
511                 -> CoreExpr     -- Expression to which the pattern is bound
512                 -> DsM [(Id,CoreExpr)]
513
514 mkSelectorBinds (L _ (VarPat v)) val_expr
515   = return [(v, val_expr)]
516
517 mkSelectorBinds pat val_expr
518   | isSingleton binders || is_simple_lpat pat = do
519         -- Given   p = e, where p binds x,y
520         -- we are going to make
521         --      v = p   (where v is fresh)
522         --      x = case v of p -> x
523         --      y = case v of p -> x
524
525         -- Make up 'v'
526         -- NB: give it the type of *pattern* p, not the type of the *rhs* e.
527         -- This does not matter after desugaring, but there's a subtle 
528         -- issue with implicit parameters. Consider
529         --      (x,y) = ?i
530         -- Then, ?i is given type {?i :: Int}, a PredType, which is opaque
531         -- to the desugarer.  (Why opaque?  Because newtypes have to be.  Why
532         -- does it get that type?  So that when we abstract over it we get the
533         -- right top-level type  (?i::Int) => ...)
534         --
535         -- So to get the type of 'v', use the pattern not the rhs.  Often more
536         -- efficient too.
537       val_var <- newSysLocalDs (hsLPatType pat)
538
539         -- For the error message we make one error-app, to avoid duplication.
540         -- But we need it at different types... so we use coerce for that
541       err_expr <- mkErrorAppDs iRREFUT_PAT_ERROR_ID  unitTy (ppr pat)
542       err_var <- newSysLocalDs unitTy
543       binds <- mapM (mk_bind val_var err_var) binders
544       return ( (val_var, val_expr) : 
545                (err_var, err_expr) :
546                binds )
547
548
549   | otherwise = do
550       error_expr <- mkErrorAppDs iRREFUT_PAT_ERROR_ID   tuple_ty (ppr pat)
551       tuple_expr <- matchSimply val_expr PatBindRhs pat local_tuple error_expr
552       tuple_var <- newSysLocalDs tuple_ty
553       let mk_tup_bind binder
554             = (binder, mkTupleSelector binders binder tuple_var (Var tuple_var))
555       return ( (tuple_var, tuple_expr) : map mk_tup_bind binders )
556   where
557     binders     = collectPatBinders pat
558     local_tuple = mkBigCoreVarTup binders
559     tuple_ty    = exprType local_tuple
560
561     mk_bind scrut_var err_var bndr_var = do
562     -- (mk_bind sv err_var) generates
563     --          bv = case sv of { pat -> bv; other -> coerce (type-of-bv) err_var }
564     -- Remember, pat binds bv
565         rhs_expr <- matchSimply (Var scrut_var) PatBindRhs pat
566                                 (Var bndr_var) error_expr
567         return (bndr_var, rhs_expr)
568       where
569         error_expr = mkCoerce co (Var err_var)
570         co         = mkUnsafeCoercion (exprType (Var err_var)) (idType bndr_var)
571
572     is_simple_lpat p = is_simple_pat (unLoc p)
573
574     is_simple_pat (TuplePat ps Boxed _)        = all is_triv_lpat ps
575     is_simple_pat (ConPatOut{ pat_args = ps }) = all is_triv_lpat (hsConPatArgs ps)
576     is_simple_pat (VarPat _)                   = True
577     is_simple_pat (ParPat p)                   = is_simple_lpat p
578     is_simple_pat _                                    = False
579
580     is_triv_lpat p = is_triv_pat (unLoc p)
581
582     is_triv_pat (VarPat _)  = True
583     is_triv_pat (WildPat _) = True
584     is_triv_pat (ParPat p)  = is_triv_lpat p
585     is_triv_pat _           = False
586
587 \end{code}
588
589 Creating big tuples and their types for full Haskell expressions.
590 They work over *Ids*, and create tuples replete with their types,
591 which is whey they are not in HsUtils.
592
593 \begin{code}
594 mkLHsPatTup :: [LPat Id] -> LPat Id
595 mkLHsPatTup []     = noLoc $ mkVanillaTuplePat [] Boxed
596 mkLHsPatTup [lpat] = lpat
597 mkLHsPatTup lpats  = L (getLoc (head lpats)) $ 
598                      mkVanillaTuplePat lpats Boxed
599
600 mkLHsVarPatTup :: [Id] -> LPat Id
601 mkLHsVarPatTup bs  = mkLHsPatTup (map nlVarPat bs)
602
603 mkVanillaTuplePat :: [OutPat Id] -> Boxity -> Pat Id
604 -- A vanilla tuple pattern simply gets its type from its sub-patterns
605 mkVanillaTuplePat pats box 
606   = TuplePat pats box (mkTupleTy box (map hsLPatType pats))
607
608 -- The Big equivalents for the source tuple expressions
609 mkBigLHsVarTup :: [Id] -> LHsExpr Id
610 mkBigLHsVarTup ids = mkBigLHsTup (map nlHsVar ids)
611
612 mkBigLHsTup :: [LHsExpr Id] -> LHsExpr Id
613 mkBigLHsTup = mkChunkified mkLHsTupleExpr
614
615 -- The Big equivalents for the source tuple patterns
616 mkBigLHsVarPatTup :: [Id] -> LPat Id
617 mkBigLHsVarPatTup bs = mkBigLHsPatTup (map nlVarPat bs)
618
619 mkBigLHsPatTup :: [LPat Id] -> LPat Id
620 mkBigLHsPatTup = mkChunkified mkLHsPatTup
621 \end{code}
622
623 %************************************************************************
624 %*                                                                      *
625 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
626 %*                                                                      *
627 %************************************************************************
628
629 Generally, we handle pattern matching failure like this: let-bind a
630 fail-variable, and use that variable if the thing fails:
631 \begin{verbatim}
632         let fail.33 = error "Help"
633         in
634         case x of
635                 p1 -> ...
636                 p2 -> fail.33
637                 p3 -> fail.33
638                 p4 -> ...
639 \end{verbatim}
640 Then
641 \begin{itemize}
642 \item
643 If the case can't fail, then there'll be no mention of @fail.33@, and the
644 simplifier will later discard it.
645
646 \item
647 If it can fail in only one way, then the simplifier will inline it.
648
649 \item
650 Only if it is used more than once will the let-binding remain.
651 \end{itemize}
652
653 There's a problem when the result of the case expression is of
654 unboxed type.  Then the type of @fail.33@ is unboxed too, and
655 there is every chance that someone will change the let into a case:
656 \begin{verbatim}
657         case error "Help" of
658           fail.33 -> case ....
659 \end{verbatim}
660
661 which is of course utterly wrong.  Rather than drop the condition that
662 only boxed types can be let-bound, we just turn the fail into a function
663 for the primitive case:
664 \begin{verbatim}
665         let fail.33 :: Void -> Int#
666             fail.33 = \_ -> error "Help"
667         in
668         case x of
669                 p1 -> ...
670                 p2 -> fail.33 void
671                 p3 -> fail.33 void
672                 p4 -> ...
673 \end{verbatim}
674
675 Now @fail.33@ is a function, so it can be let-bound.
676
677 \begin{code}
678 mkFailurePair :: CoreExpr       -- Result type of the whole case expression
679               -> DsM (CoreBind, -- Binds the newly-created fail variable
680                                 -- to \ _ -> expression
681                       CoreExpr) -- Fail variable applied to realWorld#
682 -- See Note [Failure thunks and CPR]
683 mkFailurePair expr
684   = do { fail_fun_var <- newFailLocalDs (realWorldStatePrimTy `mkFunTy` ty)
685        ; fail_fun_arg <- newSysLocalDs realWorldStatePrimTy
686        ; return (NonRec fail_fun_var (Lam fail_fun_arg expr),
687                  App (Var fail_fun_var) (Var realWorldPrimId)) }
688   where
689     ty = exprType expr
690 \end{code}
691
692 Note [Failure thunks and CPR]
693 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
694 When we make a failure point we ensure that it
695 does not look like a thunk. Example:
696
697    let fail = \rw -> error "urk"
698    in case x of 
699         [] -> fail realWorld#
700         (y:ys) -> case ys of
701                     [] -> fail realWorld#  
702                     (z:zs) -> (y,z)
703
704 Reason: we know that a failure point is always a "join point" and is
705 entered at most once.  Adding a dummy 'realWorld' token argument makes
706 it clear that sharing is not an issue.  And that in turn makes it more
707 CPR-friendly.  This matters a lot: if you don't get it right, you lose
708 the tail call property.  For example, see Trac #3403.
709
710 \begin{code}
711 mkOptTickBox :: Maybe (Int,[Id]) -> CoreExpr -> DsM CoreExpr
712 mkOptTickBox Nothing e   = return e
713 mkOptTickBox (Just (ix,ids)) e = mkTickBox ix ids e
714
715 mkTickBox :: Int -> [Id] -> CoreExpr -> DsM CoreExpr
716 mkTickBox ix vars e = do
717        uq <- newUnique  
718        mod <- getModuleDs
719        let tick | opt_Hpc   = mkTickBoxOpId uq mod ix
720                 | otherwise = mkBreakPointOpId uq mod ix
721        uq2 <- newUnique         
722        let occName = mkVarOcc "tick"
723        let name = mkInternalName uq2 occName noSrcSpan   -- use mkSysLocal?
724        let var  = Id.mkLocalId name realWorldStatePrimTy
725        scrut <- 
726           if opt_Hpc 
727             then return (Var tick)
728             else do
729               let tickVar = Var tick
730               let tickType = mkFunTys (map idType vars) realWorldStatePrimTy 
731               let scrutApTy = App tickVar (Type tickType)
732               return (mkApps scrutApTy (map Var vars) :: Expr Id)
733        return $ Case scrut var ty [(DEFAULT,[],e)]
734   where
735      ty = exprType e
736
737 mkBinaryTickBox :: Int -> Int -> CoreExpr -> DsM CoreExpr
738 mkBinaryTickBox ixT ixF e = do
739        uq <- newUnique  
740        let bndr1 = mkSysLocal (fsLit "t1") uq boolTy 
741        falseBox <- mkTickBox ixF [] $ Var falseDataConId
742        trueBox  <- mkTickBox ixT [] $ Var trueDataConId
743        return $ Case e bndr1 boolTy
744                        [ (DataAlt falseDataCon, [], falseBox)
745                        , (DataAlt trueDataCon,  [], trueBox)
746                        ]
747 \end{code}