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 #2231
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. 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.
455 The reason it's a hack is because if you define mySeq=seq, the hack
458 Note [Desugaring seq (3)] cf Trac #2409
459 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
460 The isLocalId ensures that we don't turn
463 case True of True { ... }
464 which stupidly tries to bind the datacon 'True'.
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)]
472 case_bndr = case arg1 of
473 Var v1 | isLocalId v1 -> v1 -- Note [Desugaring seq (2) and (3)]
474 _ -> mkWildBinder ty1
476 mkCoreAppDs fun arg = mkCoreApp fun arg -- The rest is done in MkCore
478 mkCoreAppsDs :: CoreExpr -> [CoreExpr] -> CoreExpr
479 mkCoreAppsDs fun args = foldl mkCoreAppDs fun args
483 %************************************************************************
485 \subsection[mkSelectorBind]{Make a selector bind}
487 %************************************************************************
489 This is used in various places to do with lazy patterns.
490 For each binder $b$ in the pattern, we create a binding:
492 b = case v of pat' -> b'
494 where @pat'@ is @pat@ with each binder @b@ cloned into @b'@.
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).
501 Boring! Boring! One error message per binder. The above ToDo is
502 even more helpful. Something very similar happens for pattern-bound
506 mkSelectorBinds :: LPat Id -- The pattern
507 -> CoreExpr -- Expression to which the pattern is bound
508 -> DsM [(Id,CoreExpr)]
510 mkSelectorBinds (L _ (VarPat v)) val_expr
511 = return [(v, val_expr)]
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
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
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) => ...)
531 -- So to get the type of 'v', use the pattern not the rhs. Often more
533 val_var <- newSysLocalDs (hsLPatType pat)
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) :
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
551 = (binder, mkTupleSelector binders binder tuple_var (Var tuple_var))
552 return ( (tuple_var, tuple_expr) : map mk_tup_bind binders )
554 binders = collectPatBinders pat
555 local_tuple = mkBigCoreVarTup binders
556 tuple_ty = exprType local_tuple
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)
566 error_expr = mkCoerce co (Var err_var)
567 co = mkUnsafeCoercion (exprType (Var err_var)) (idType bndr_var)
569 is_simple_lpat p = is_simple_pat (unLoc p)
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
577 is_triv_lpat p = is_triv_pat (unLoc p)
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
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.
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
597 mkLHsVarPatTup :: [Id] -> LPat Id
598 mkLHsVarPatTup bs = mkLHsPatTup (map nlVarPat bs)
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))
605 -- The Big equivalents for the source tuple expressions
606 mkBigLHsVarTup :: [Id] -> LHsExpr Id
607 mkBigLHsVarTup ids = mkBigLHsTup (map nlHsVar ids)
609 mkBigLHsTup :: [LHsExpr Id] -> LHsExpr Id
610 mkBigLHsTup = mkChunkified mkLHsTupleExpr
612 -- The Big equivalents for the source tuple patterns
613 mkBigLHsVarPatTup :: [Id] -> LPat Id
614 mkBigLHsVarPatTup bs = mkBigLHsPatTup (map nlVarPat bs)
616 mkBigLHsPatTup :: [LPat Id] -> LPat Id
617 mkBigLHsPatTup = mkChunkified mkLHsPatTup
620 %************************************************************************
622 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
624 %************************************************************************
626 Generally, we handle pattern matching failure like this: let-bind a
627 fail-variable, and use that variable if the thing fails:
629 let fail.33 = error "Help"
640 If the case can't fail, then there'll be no mention of @fail.33@, and the
641 simplifier will later discard it.
644 If it can fail in only one way, then the simplifier will inline it.
647 Only if it is used more than once will the let-binding remain.
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:
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:
662 let fail.33 :: Void -> Int#
663 fail.33 = \_ -> error "Help"
672 Now @fail.33@ is a function, so it can be let-bound.
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]
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)) }
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:
694 let fail = \rw -> error "urk"
696 [] -> fail realWorld#
698 [] -> fail realWorld#
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.
708 mkOptTickBox :: Maybe (Int,[Id]) -> CoreExpr -> DsM CoreExpr
709 mkOptTickBox Nothing e = return e
710 mkOptTickBox (Just (ix,ids)) e = mkTickBox ix ids e
712 mkTickBox :: Int -> [Id] -> CoreExpr -> DsM CoreExpr
713 mkTickBox ix vars e = do
716 let tick | opt_Hpc = mkTickBoxOpId uq mod ix
717 | otherwise = mkBreakPointOpId uq mod ix
719 let occName = mkVarOcc "tick"
720 let name = mkInternalName uq2 occName noSrcSpan -- use mkSysLocal?
721 let var = Id.mkLocalId name realWorldStatePrimTy
724 then return (Var tick)
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)]
734 mkBinaryTickBox :: Int -> Int -> CoreExpr -> DsM CoreExpr
735 mkBinaryTickBox ixT ixF e = do
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)