2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Utilities for desugaring
8 This module exports some utility functions of no great interest.
11 -- | Utility functions for constructing Core syntax, principally for desugaring
16 MatchResult(..), CanItFail(..),
17 cantFailMatchResult, alwaysFailMatchResult,
18 extractMatchResult, combineMatchResults,
19 adjustMatchResult, adjustMatchResultDs,
20 mkCoLetMatchResult, mkViewMatchResult, mkGuardedMatchResult,
21 matchCanFail, mkEvalMatchResult,
22 mkCoPrimCaseMatchResult, mkCoAlgCaseMatchResult,
25 mkErrorAppDs, mkCoreAppDs, mkCoreAppsDs,
30 mkLHsVarPatTup, mkLHsPatTup, mkVanillaTuplePat,
31 mkBigLHsVarTup, mkBigLHsTup, mkBigLHsVarPatTup, mkBigLHsPatTup,
35 dsSyntaxTable, lookupEvidence,
37 selectSimpleMatchVarL, selectMatchVars, selectMatchVar,
38 mkTickBox, mkOptTickBox, mkBinaryTickBox
41 #include "HsVersions.h"
43 import {-# SOURCE #-} Match ( matchSimply )
44 import {-# SOURCE #-} DsExpr( dsExpr )
48 import TcType( tcSplitTyConApp )
79 %************************************************************************
83 %************************************************************************
86 dsSyntaxTable :: SyntaxTable Id
87 -> DsM ([CoreBind], -- Auxiliary bindings
88 [(Name,Id)]) -- Maps the standard name to its value
90 dsSyntaxTable rebound_ids = do
91 (binds_s, prs) <- mapAndUnzipM mk_bind rebound_ids
92 return (concat binds_s, prs)
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
99 id <- newSysLocalDs (exprType rhs)
100 return ([NonRec id rhs], (std_name, id))
102 lookupEvidence :: [(Name, Id)] -> Name -> Id
103 lookupEvidence prs std_name
104 = assocDefault (mk_panic std_name) prs std_name
106 mk_panic std_name = pprPanic "dsSyntaxTable" (ptext (sLit "Not found:") <+> ppr std_name)
109 %************************************************************************
111 \subsection{ Selecting match variables}
113 %************************************************************************
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.
121 selectSimpleMatchVarL :: LPat Id -> DsM Id
122 selectSimpleMatchVarL pat = selectMatchVar (unLoc pat)
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.
128 -- OLD, but interesting note:
129 -- But even if it is a variable, its type might not match. Consider
131 -- T1 :: Int -> T Int
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
140 selectMatchVars :: [Pat Id] -> DsM [Id]
141 selectMatchVars ps = mapM selectMatchVar ps
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...
154 %************************************************************************
156 %* type synonym EquationInfo and access functions for its pieces *
158 %************************************************************************
159 \subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
161 The ``equation info'' used by @match@ is relatively complicated and
162 worthy of a type synonym and a few handy functions.
165 firstPat :: EquationInfo -> Pat Id
166 firstPat eqn = ASSERT( notNull (eqn_pats eqn) ) head (eqn_pats eqn)
168 shiftEqns :: [EquationInfo] -> [EquationInfo]
169 -- Drop the first pattern in each equation
170 shiftEqns eqns = [ eqn { eqn_pats = tail (eqn_pats eqn) } | eqn <- eqns ]
173 Functions on MatchResults
176 matchCanFail :: MatchResult -> Bool
177 matchCanFail (MatchResult CanFail _) = True
178 matchCanFail (MatchResult CantFail _) = False
180 alwaysFailMatchResult :: MatchResult
181 alwaysFailMatchResult = MatchResult CanFail (\fail -> return fail)
183 cantFailMatchResult :: CoreExpr -> MatchResult
184 cantFailMatchResult expr = MatchResult CantFail (\_ -> return expr)
186 extractMatchResult :: MatchResult -> CoreExpr -> DsM CoreExpr
187 extractMatchResult (MatchResult CantFail match_fn) _
188 = match_fn (error "It can't fail!")
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)
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
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)
206 combineMatchResults match_result1@(MatchResult CantFail _) _
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)
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)
217 wrapBinds :: [(Var,Var)] -> CoreExpr -> CoreExpr
219 wrapBinds ((new,old):prs) e = wrapBind new old (wrapBinds prs e)
221 wrapBind :: Var -> Var -> CoreExpr -> CoreExpr
222 wrapBind new old body -- Can deal with term variables *or* type variables
224 | isTyVar new = Let (mkTyBind new (mkTyVarTy old)) body
225 | otherwise = Let (NonRec new (Var old)) body
227 seqVar :: Var -> CoreExpr -> CoreExpr
228 seqVar var body = Case (Var var) var (exprType body)
229 [(DEFAULT, [], body)]
231 mkCoLetMatchResult :: CoreBind -> MatchResult -> MatchResult
232 mkCoLetMatchResult bind = adjustMatchResult (mkCoreLet bind)
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))))
240 mkEvalMatchResult :: Id -> Type -> MatchResult -> MatchResult
241 mkEvalMatchResult var ty
242 = adjustMatchResult (\e -> Case (Var var) var ty [(DEFAULT, [], e)])
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))
249 mkCoPrimCaseMatchResult :: Id -- Scrutinee
250 -> Type -- Type of the case
251 -> [(Literal, MatchResult)] -- Alternatives
253 mkCoPrimCaseMatchResult var ty match_alts
254 = MatchResult CanFail mk_case
257 alts <- mapM (mk_alt fail) sorted_alts
258 return (Case (Var var) var ty ((DEFAULT, [], fail) : alts))
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)
265 mkCoAlgCaseMatchResult :: Id -- Scrutinee
266 -> Type -- Type of exp
267 -> [(DataCon, [CoreBndr], MatchResult)] -- Alternatives
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
274 | isPArrFakeAlts match_alts -- Sugared parallel array; use a literal case
275 = MatchResult CanFail mk_parrCase
277 | otherwise -- Datatype case; use a case
278 = MatchResult fail_flag mk_case
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]
285 (con1, arg_ids1, match_result1) = ASSERT( notNull match_alts ) head match_alts
286 arg_id1 = ASSERT( notNull arg_ids1 ) head arg_ids1
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)
292 -- Stuff for data types
293 data_cons = tyConDataCons tycon
294 match_results = [match_result | (_,_,match_result) <- match_alts]
296 fail_flag | exhaustive_case
297 = foldr1 orFail [can_it_fail | MatchResult can_it_fail _ <- match_results]
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))
306 mk_alt fail (con, args, MatchResult _ body_fn) = do
308 us <- newUniqueSupply
309 return (mkReboxingAlt (uniqsFromSupply us) con args body)
311 mk_default fail | exhaustive_case = []
312 | otherwise = [(DEFAULT, [], fail)]
314 un_mentioned_constructors
315 = mkUniqSet data_cons `minusUniqSet` mkUniqSet [ con | (con, _, _) <- match_alts]
316 exhaustive_case = isEmptyUniqSet un_mentioned_constructors
318 -- Stuff for parallel arrays
320 -- * the following is to desugar cases over fake constructors for
321 -- parallel arrays, which are introduced by `tidy1' in the `PArrPat'
324 -- Concerning `isPArrFakeAlts':
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)
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.
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"
348 mk_parrCase fail = do
349 lengthP <- dsLookupGlobalId lengthPName
351 return (mkWildCase (len lengthP) intTy ty [alt])
353 elemTy = case splitTyConApp (idType var) of
354 (_, [elemTy]) -> elemTy
356 panicMsg = "DsUtils.mkCoAlgCaseMatchResult: not a parallel array?"
357 len lengthP = mkApps (Var lengthP) [Type elemTy, Var var]
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))
365 dft = (DEFAULT, [], fail)
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
373 mkAlt indexP (con, args, MatchResult _ bodyFun) = do
375 return (LitAlt lit, [], mkCoreLets binds body)
377 lit = MachInt $ toInteger (dataConSourceArity con)
378 binds = [NonRec arg (indexExpr i) | (i, arg) <- zip [1..] args]
380 indexExpr i = mkApps (Var indexP) [Type elemTy, Var var, mkIntExpr i]
383 %************************************************************************
385 \subsection{Desugarer's versions of some Core functions}
387 %************************************************************************
390 mkErrorAppDs :: Id -- The error function
391 -> Type -- Type to which it should be applied
392 -> SDoc -- The error message string to pass
395 mkErrorAppDs err_id ty msg = do
396 src_loc <- getSrcSpanDs
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])
404 'mkCoreAppDs' and 'mkCoreAppsDs' hand the special-case desugaring of 'seq'.
406 Note [Desugaring seq (1)] cf Trac #1031
407 ~~~~~~~~~~~~~~~~~~~~~~~~~
408 f x y = x `seq` (y `seq` (# x,y #))
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:
413 f x y = case (y `seq` (# x,y #)) of v -> x `seq` v
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
419 Seq is very, very special! So we recognise it right here, and desugar to
420 case x of _ -> case y of _ -> (# x,y #)
422 Note [Desugaring seq (2)] cf Trac #2273
423 ~~~~~~~~~~~~~~~~~~~~~~~~~
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)
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... }
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}...
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...
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
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... }
459 The reason it's a hack is because if you define mySeq=seq, the hack
462 Note [Desugaring seq (3)] cf Trac #2409
463 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
464 The isLocalId ensures that we don't turn
467 case True of True { ... }
468 which stupidly tries to bind the datacon 'True'.
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)]
476 case_bndr = case arg1 of
477 Var v1 | isLocalId v1 -> v1 -- Note [Desugaring seq (2) and (3)]
478 _ -> mkWildBinder ty1
480 mkCoreAppDs fun arg = mkCoreApp fun arg -- The rest is done in MkCore
482 mkCoreAppsDs :: CoreExpr -> [CoreExpr] -> CoreExpr
483 mkCoreAppsDs fun args = foldl mkCoreAppDs fun args
487 %************************************************************************
489 \subsection[mkSelectorBind]{Make a selector bind}
491 %************************************************************************
493 This is used in various places to do with lazy patterns.
494 For each binder $b$ in the pattern, we create a binding:
496 b = case v of pat' -> b'
498 where @pat'@ is @pat@ with each binder @b@ cloned into @b'@.
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).
505 Boring! Boring! One error message per binder. The above ToDo is
506 even more helpful. Something very similar happens for pattern-bound
510 mkSelectorBinds :: LPat Id -- The pattern
511 -> CoreExpr -- Expression to which the pattern is bound
512 -> DsM [(Id,CoreExpr)]
514 mkSelectorBinds (L _ (VarPat v)) val_expr
515 = return [(v, val_expr)]
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
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
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) => ...)
535 -- So to get the type of 'v', use the pattern not the rhs. Often more
537 val_var <- newSysLocalDs (hsLPatType pat)
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) :
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
555 = (binder, mkTupleSelector binders binder tuple_var (Var tuple_var))
556 return ( (tuple_var, tuple_expr) : map mk_tup_bind binders )
558 binders = collectPatBinders pat
559 local_tuple = mkBigCoreVarTup binders
560 tuple_ty = exprType local_tuple
562 mk_bind scrut_var err_var bndr_var = do
563 -- (mk_bind sv err_var) generates
564 -- bv = case sv of { pat -> bv; other -> coerce (type-of-bv) err_var }
565 -- Remember, pat binds bv
566 rhs_expr <- matchSimply (Var scrut_var) PatBindRhs pat
567 (Var bndr_var) error_expr
568 return (bndr_var, rhs_expr)
570 error_expr = mkCoerce co (Var err_var)
571 co = mkUnsafeCoercion (exprType (Var err_var)) (idType bndr_var)
573 is_simple_lpat p = is_simple_pat (unLoc p)
575 is_simple_pat (TuplePat ps Boxed _) = all is_triv_lpat ps
576 is_simple_pat (ConPatOut{ pat_args = ps }) = all is_triv_lpat (hsConPatArgs ps)
577 is_simple_pat (VarPat _) = True
578 is_simple_pat (ParPat p) = is_simple_lpat p
579 is_simple_pat _ = False
581 is_triv_lpat p = is_triv_pat (unLoc p)
583 is_triv_pat (VarPat _) = True
584 is_triv_pat (WildPat _) = True
585 is_triv_pat (ParPat p) = is_triv_lpat p
586 is_triv_pat _ = False
590 Creating big tuples and their types for full Haskell expressions.
591 They work over *Ids*, and create tuples replete with their types,
592 which is whey they are not in HsUtils.
595 mkLHsPatTup :: [LPat Id] -> LPat Id
596 mkLHsPatTup [] = noLoc $ mkVanillaTuplePat [] Boxed
597 mkLHsPatTup [lpat] = lpat
598 mkLHsPatTup lpats = L (getLoc (head lpats)) $
599 mkVanillaTuplePat lpats Boxed
601 mkLHsVarPatTup :: [Id] -> LPat Id
602 mkLHsVarPatTup bs = mkLHsPatTup (map nlVarPat bs)
604 mkVanillaTuplePat :: [OutPat Id] -> Boxity -> Pat Id
605 -- A vanilla tuple pattern simply gets its type from its sub-patterns
606 mkVanillaTuplePat pats box
607 = TuplePat pats box (mkTupleTy box (length pats) (map hsLPatType pats))
609 -- The Big equivalents for the source tuple expressions
610 mkBigLHsVarTup :: [Id] -> LHsExpr Id
611 mkBigLHsVarTup ids = mkBigLHsTup (map nlHsVar ids)
613 mkBigLHsTup :: [LHsExpr Id] -> LHsExpr Id
614 mkBigLHsTup = mkChunkified mkLHsTupleExpr
616 -- The Big equivalents for the source tuple patterns
617 mkBigLHsVarPatTup :: [Id] -> LPat Id
618 mkBigLHsVarPatTup bs = mkBigLHsPatTup (map nlVarPat bs)
620 mkBigLHsPatTup :: [LPat Id] -> LPat Id
621 mkBigLHsPatTup = mkChunkified mkLHsPatTup
624 %************************************************************************
626 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
628 %************************************************************************
630 Generally, we handle pattern matching failure like this: let-bind a
631 fail-variable, and use that variable if the thing fails:
633 let fail.33 = error "Help"
644 If the case can't fail, then there'll be no mention of @fail.33@, and the
645 simplifier will later discard it.
648 If it can fail in only one way, then the simplifier will inline it.
651 Only if it is used more than once will the let-binding remain.
654 There's a problem when the result of the case expression is of
655 unboxed type. Then the type of @fail.33@ is unboxed too, and
656 there is every chance that someone will change the let into a case:
662 which is of course utterly wrong. Rather than drop the condition that
663 only boxed types can be let-bound, we just turn the fail into a function
664 for the primitive case:
666 let fail.33 :: Void -> Int#
667 fail.33 = \_ -> error "Help"
676 Now @fail.33@ is a function, so it can be let-bound.
679 mkFailurePair :: CoreExpr -- Result type of the whole case expression
680 -> DsM (CoreBind, -- Binds the newly-created fail variable
681 -- to \ _ -> expression
682 CoreExpr) -- Fail variable applied to realWorld#
683 -- See Note [Failure thunks and CPR]
685 = do { fail_fun_var <- newFailLocalDs (realWorldStatePrimTy `mkFunTy` ty)
686 ; fail_fun_arg <- newSysLocalDs realWorldStatePrimTy
687 ; return (NonRec fail_fun_var (Lam fail_fun_arg expr),
688 App (Var fail_fun_var) (Var realWorldPrimId)) }
693 Note [Failure thunks and CPR]
694 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
695 When we make a failure point we ensure that it
696 does not look like a thunk. Example:
698 let fail = \rw -> error "urk"
700 [] -> fail realWorld#
702 [] -> fail realWorld#
705 Reason: we know that a failure point is always a "join point" and is
706 entered at most once. Adding a dummy 'realWorld' token argument makes
707 it clear that sharing is not an issue. And that in turn makes it more
708 CPR-friendly. This matters a lot: if you don't get it right, you lose
709 the tail call property. For example, see Trac #3403.
712 mkOptTickBox :: Maybe (Int,[Id]) -> CoreExpr -> DsM CoreExpr
713 mkOptTickBox Nothing e = return e
714 mkOptTickBox (Just (ix,ids)) e = mkTickBox ix ids e
716 mkTickBox :: Int -> [Id] -> CoreExpr -> DsM CoreExpr
717 mkTickBox ix vars e = do
720 let tick | opt_Hpc = mkTickBoxOpId uq mod ix
721 | otherwise = mkBreakPointOpId uq mod ix
723 let occName = mkVarOcc "tick"
724 let name = mkInternalName uq2 occName noSrcSpan -- use mkSysLocal?
725 let var = Id.mkLocalId name realWorldStatePrimTy
728 then return (Var tick)
730 let tickVar = Var tick
731 let tickType = mkFunTys (map idType vars) realWorldStatePrimTy
732 let scrutApTy = App tickVar (Type tickType)
733 return (mkApps scrutApTy (map Var vars) :: Expr Id)
734 return $ Case scrut var ty [(DEFAULT,[],e)]
738 mkBinaryTickBox :: Int -> Int -> CoreExpr -> DsM CoreExpr
739 mkBinaryTickBox ixT ixF e = do
741 let bndr1 = mkSysLocal (fsLit "t1") uq boolTy
742 falseBox <- mkTickBox ixF [] $ Var falseDataConId
743 trueBox <- mkTickBox ixT [] $ Var trueDataConId
744 return $ Case e bndr1 boolTy
745 [ (DataAlt falseDataCon, [], falseBox)
746 , (DataAlt trueDataCon, [], trueBox)