2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[DsUtils]{Utilities for desugaring}
6 This module exports some utility functions of no great interest.
10 CanItFail(..), EquationInfo(..), MatchResult(..),
17 cantFailMatchResult, extractMatchResult,
19 adjustMatchResult, adjustMatchResultDs,
20 mkCoLetsMatchResult, mkGuardedMatchResult,
21 mkCoPrimCaseMatchResult, mkCoAlgCaseMatchResult,
23 mkErrorAppDs, mkNilExpr, mkConsExpr, mkListExpr,
24 mkIntExpr, mkCharExpr,
25 mkStringLit, mkStringLitFS, mkIntegerExpr,
27 mkSelectorBinds, mkTupleExpr, mkTupleSelector,
28 mkCoreTup, mkCoreSel, mkCoreTupTy,
30 dsReboundNames, lookupReboundName,
35 #include "HsVersions.h"
37 import {-# SOURCE #-} Match ( matchSimply )
38 import {-# SOURCE #-} DsExpr( dsExpr )
41 import TcHsSyn ( TypecheckedPat, hsPatType )
43 import Constants ( mAX_TUPLE_SIZE )
46 import CoreUtils ( exprType, mkIfThenElse, mkCoerce )
47 import MkId ( iRREFUT_PAT_ERROR_ID, mkReboxingAlt, mkNewTypeBody )
48 import Id ( idType, Id, mkWildId, mkTemplateLocals )
50 import Literal ( Literal(..), inIntRange, tARGET_MAX_INT )
51 import TyCon ( isNewTyCon, tyConDataCons )
52 import DataCon ( DataCon, dataConSourceArity )
53 import Type ( mkFunTy, isUnLiftedType, Type, splitTyConApp )
54 import TcType ( tcTyConAppTyCon, isIntTy, isFloatTy, isDoubleTy )
55 import TysPrim ( intPrimTy )
56 import TysWiredIn ( nilDataCon, consDataCon,
58 unitDataConId, unitTy,
60 intTy, intDataCon, smallIntegerDataCon,
63 stringTy, isPArrFakeCon )
64 import BasicTypes ( Boxity(..) )
65 import UniqSet ( mkUniqSet, minusUniqSet, isEmptyUniqSet, UniqSet )
66 import PrelNames ( unpackCStringName, unpackCStringUtf8Name,
67 plusIntegerName, timesIntegerName,
68 lengthPName, indexPName )
70 import UnicodeUtil ( intsToUtf8, stringToUtf8 )
71 import Util ( isSingleton, notNull, zipEqual )
72 import ListSetOps ( assocDefault )
78 %************************************************************************
82 %************************************************************************
85 dsReboundNames :: ReboundNames Id
86 -> DsM ([CoreBind], -- Auxiliary bindings
87 [(Name,Id)]) -- Maps the standard name to its value
89 dsReboundNames rebound_ids
90 = mapAndUnzipDs mk_bind rebound_ids `thenDs` \ (binds_s, prs) ->
91 return (concat binds_s, prs)
93 -- The cheapo special case can happen when we
94 -- make an intermediate HsDo when desugaring a RecStmt
95 mk_bind (std_name, HsVar id) = return ([], (std_name, id))
96 mk_bind (std_name, expr) = dsExpr expr `thenDs` \ rhs ->
97 newSysLocalDs (exprType rhs) `thenDs` \ id ->
98 return ([NonRec id rhs], (std_name, id))
100 lookupReboundName :: [(Name,Id)] -> Name -> CoreExpr
101 lookupReboundName prs std_name
102 = Var (assocDefault (mk_panic std_name) prs std_name)
104 mk_panic std_name = pprPanic "dsReboundNames" (ptext SLIT("Not found:") <+> ppr std_name)
108 %************************************************************************
110 \subsection{Tidying lit pats}
112 %************************************************************************
115 tidyLitPat :: HsLit -> TypecheckedPat -> TypecheckedPat
116 tidyLitPat (HsChar c) pat = mkCharLitPat c
117 tidyLitPat lit pat = pat
119 tidyNPat :: HsLit -> Type -> TypecheckedPat -> TypecheckedPat
120 tidyNPat (HsString s) _ pat
121 | lengthFS s <= 1 -- Short string literals only
122 = foldr (\c pat -> mkPrefixConPat consDataCon [mkCharLitPat c,pat] stringTy)
123 (mkNilPat stringTy) (unpackIntFS s)
124 -- The stringTy is the type of the whole pattern, not
125 -- the type to instantiate (:) or [] with!
128 tidyNPat lit lit_ty default_pat
129 | isIntTy lit_ty = mkPrefixConPat intDataCon [LitPat (mk_int lit)] lit_ty
130 | isFloatTy lit_ty = mkPrefixConPat floatDataCon [LitPat (mk_float lit)] lit_ty
131 | isDoubleTy lit_ty = mkPrefixConPat doubleDataCon [LitPat (mk_double lit)] lit_ty
132 | otherwise = default_pat
135 mk_int (HsInteger i) = HsIntPrim i
137 mk_float (HsInteger i) = HsFloatPrim (fromInteger i)
138 mk_float (HsRat f _) = HsFloatPrim f
140 mk_double (HsInteger i) = HsDoublePrim (fromInteger i)
141 mk_double (HsRat f _) = HsDoublePrim f
145 %************************************************************************
147 \subsection{Building lets}
149 %************************************************************************
151 Use case, not let for unlifted types. The simplifier will turn some
155 mkDsLet :: CoreBind -> CoreExpr -> CoreExpr
156 mkDsLet (NonRec bndr rhs) body
157 | isUnLiftedType (idType bndr) = Case rhs bndr [(DEFAULT,[],body)]
161 mkDsLets :: [CoreBind] -> CoreExpr -> CoreExpr
162 mkDsLets binds body = foldr mkDsLet body binds
166 %************************************************************************
168 \subsection{ Selecting match variables}
170 %************************************************************************
172 We're about to match against some patterns. We want to make some
173 @Ids@ to use as match variables. If a pattern has an @Id@ readily at
174 hand, which should indeed be bound to the pattern as a whole, then use it;
175 otherwise, make one up.
178 selectMatchVar :: TypecheckedPat -> DsM Id
179 selectMatchVar (VarPat var) = returnDs var
180 selectMatchVar (AsPat var pat) = returnDs var
181 selectMatchVar (LazyPat pat) = selectMatchVar pat
182 selectMatchVar other_pat = newSysLocalDs (hsPatType other_pat) -- OK, better make up one...
186 %************************************************************************
188 %* type synonym EquationInfo and access functions for its pieces *
190 %************************************************************************
191 \subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
193 The ``equation info'' used by @match@ is relatively complicated and
194 worthy of a type synonym and a few handy functions.
199 type EqnSet = UniqSet EqnNo
203 EqnNo -- The number of the equation
205 DsMatchContext -- The context info is used when producing warnings
206 -- about shadowed patterns. It's the context
207 -- of the *first* thing matched in this group.
208 -- Should perhaps be a list of them all!
210 [TypecheckedPat] -- The patterns for an eqn
212 MatchResult -- Encapsulates the guards and bindings
218 CanItFail -- Tells whether the failure expression is used
219 (CoreExpr -> DsM CoreExpr)
220 -- Takes a expression to plug in at the
221 -- failure point(s). The expression should
224 data CanItFail = CanFail | CantFail
226 orFail CantFail CantFail = CantFail
230 Functions on MatchResults
233 cantFailMatchResult :: CoreExpr -> MatchResult
234 cantFailMatchResult expr = MatchResult CantFail (\ ignore -> returnDs expr)
236 extractMatchResult :: MatchResult -> CoreExpr -> DsM CoreExpr
237 extractMatchResult (MatchResult CantFail match_fn) fail_expr
238 = match_fn (error "It can't fail!")
240 extractMatchResult (MatchResult CanFail match_fn) fail_expr
241 = mkFailurePair fail_expr `thenDs` \ (fail_bind, if_it_fails) ->
242 match_fn if_it_fails `thenDs` \ body ->
243 returnDs (mkDsLet fail_bind body)
246 combineMatchResults :: MatchResult -> MatchResult -> MatchResult
247 combineMatchResults (MatchResult CanFail body_fn1)
248 (MatchResult can_it_fail2 body_fn2)
249 = MatchResult can_it_fail2 body_fn
251 body_fn fail = body_fn2 fail `thenDs` \ body2 ->
252 mkFailurePair body2 `thenDs` \ (fail_bind, duplicatable_expr) ->
253 body_fn1 duplicatable_expr `thenDs` \ body1 ->
254 returnDs (Let fail_bind body1)
256 combineMatchResults match_result1@(MatchResult CantFail body_fn1) match_result2
260 adjustMatchResult :: (CoreExpr -> CoreExpr) -> MatchResult -> MatchResult
261 adjustMatchResult encl_fn (MatchResult can_it_fail body_fn)
262 = MatchResult can_it_fail (\fail -> body_fn fail `thenDs` \ body ->
263 returnDs (encl_fn body))
265 adjustMatchResultDs :: (CoreExpr -> DsM CoreExpr) -> MatchResult -> MatchResult
266 adjustMatchResultDs encl_fn (MatchResult can_it_fail body_fn)
267 = MatchResult can_it_fail (\fail -> body_fn fail `thenDs` \ body ->
271 mkCoLetsMatchResult :: [CoreBind] -> MatchResult -> MatchResult
272 mkCoLetsMatchResult binds match_result
273 = adjustMatchResult (mkDsLets binds) match_result
276 mkGuardedMatchResult :: CoreExpr -> MatchResult -> MatchResult
277 mkGuardedMatchResult pred_expr (MatchResult can_it_fail body_fn)
278 = MatchResult CanFail (\fail -> body_fn fail `thenDs` \ body ->
279 returnDs (mkIfThenElse pred_expr body fail))
281 mkCoPrimCaseMatchResult :: Id -- Scrutinee
282 -> [(Literal, MatchResult)] -- Alternatives
284 mkCoPrimCaseMatchResult var match_alts
285 = MatchResult CanFail mk_case
288 = mapDs (mk_alt fail) match_alts `thenDs` \ alts ->
289 returnDs (Case (Var var) var ((DEFAULT, [], fail) : alts))
291 mk_alt fail (lit, MatchResult _ body_fn) = body_fn fail `thenDs` \ body ->
292 returnDs (LitAlt lit, [], body)
295 mkCoAlgCaseMatchResult :: Id -- Scrutinee
296 -> [(DataCon, [CoreBndr], MatchResult)] -- Alternatives
299 mkCoAlgCaseMatchResult var match_alts
300 | isNewTyCon tycon -- Newtype case; use a let
301 = ASSERT( null (tail match_alts) && null (tail arg_ids) )
302 mkCoLetsMatchResult [NonRec arg_id newtype_rhs] match_result
304 | isPArrFakeAlts match_alts -- Sugared parallel array; use a literal case
305 = MatchResult CanFail mk_parrCase
307 | otherwise -- Datatype case; use a case
308 = MatchResult fail_flag mk_case
311 scrut_ty = idType var
312 tycon = tcTyConAppTyCon scrut_ty -- Newtypes must be opaque here
315 (_, arg_ids, match_result) = head match_alts
316 arg_id = head arg_ids
317 newtype_rhs = mkNewTypeBody tycon (idType arg_id) (Var var)
319 -- Stuff for data types
320 data_cons = tyConDataCons tycon
321 match_results = [match_result | (_,_,match_result) <- match_alts]
323 fail_flag | exhaustive_case
324 = foldr1 orFail [can_it_fail | MatchResult can_it_fail _ <- match_results]
328 wild_var = mkWildId (idType var)
329 mk_case fail = mapDs (mk_alt fail) match_alts `thenDs` \ alts ->
330 returnDs (Case (Var var) wild_var (mk_default fail ++ alts))
332 mk_alt fail (con, args, MatchResult _ body_fn)
333 = body_fn fail `thenDs` \ body ->
334 getUniquesDs `thenDs` \ us ->
335 returnDs (mkReboxingAlt us con args body)
337 mk_default fail | exhaustive_case = []
338 | otherwise = [(DEFAULT, [], fail)]
340 un_mentioned_constructors
341 = mkUniqSet data_cons `minusUniqSet` mkUniqSet [ con | (con, _, _) <- match_alts]
342 exhaustive_case = isEmptyUniqSet un_mentioned_constructors
344 -- Stuff for parallel arrays
346 -- * the following is to desugar cases over fake constructors for
347 -- parallel arrays, which are introduced by `tidy1' in the `PArrPat'
350 -- Concerning `isPArrFakeAlts':
352 -- * it is *not* sufficient to just check the type of the type
353 -- constructor, as we have to be careful not to confuse the real
354 -- representation of parallel arrays with the fake constructors;
355 -- moreover, a list of alternatives must not mix fake and real
356 -- constructors (this is checked earlier on)
358 -- FIXME: We actually go through the whole list and make sure that
359 -- either all or none of the constructors are fake parallel
360 -- array constructors. This is to spot equations that mix fake
361 -- constructors with the real representation defined in
362 -- `PrelPArr'. It would be nicer to spot this situation
363 -- earlier and raise a proper error message, but it can really
364 -- only happen in `PrelPArr' anyway.
366 isPArrFakeAlts [(dcon, _, _)] = isPArrFakeCon dcon
367 isPArrFakeAlts ((dcon, _, _):alts) =
368 case (isPArrFakeCon dcon, isPArrFakeAlts alts) of
369 (True , True ) -> True
370 (False, False) -> False
372 panic "DsUtils: You may not mix `[:...:]' with `PArr' patterns"
375 dsLookupGlobalId lengthPName `thenDs` \lengthP ->
376 unboxAlt `thenDs` \alt ->
377 returnDs (Case (len lengthP) (mkWildId intTy) [alt])
379 elemTy = case splitTyConApp (idType var) of
380 (_, [elemTy]) -> elemTy
382 panicMsg = "DsUtils.mkCoAlgCaseMatchResult: not a parallel array?"
383 len lengthP = mkApps (Var lengthP) [Type elemTy, Var var]
386 newSysLocalDs intPrimTy `thenDs` \l ->
387 dsLookupGlobalId indexPName `thenDs` \indexP ->
388 mapDs (mkAlt indexP) match_alts `thenDs` \alts ->
389 returnDs (DataAlt intDataCon, [l], (Case (Var l) wild (dft : alts)))
391 wild = mkWildId intPrimTy
392 dft = (DEFAULT, [], fail)
394 -- each alternative matches one array length (corresponding to one
395 -- fake array constructor), so the match is on a literal; each
396 -- alternative's body is extended by a local binding for each
397 -- constructor argument, which are bound to array elements starting
400 mkAlt indexP (con, args, MatchResult _ bodyFun) =
401 bodyFun fail `thenDs` \body ->
402 returnDs (LitAlt lit, [], mkDsLets binds body)
404 lit = MachInt $ toInteger (dataConSourceArity con)
405 binds = [NonRec arg (indexExpr i) | (i, arg) <- zip [1..] args]
407 indexExpr i = mkApps (Var indexP) [Type elemTy, Var var, mkIntExpr i]
411 %************************************************************************
413 \subsection{Desugarer's versions of some Core functions}
415 %************************************************************************
418 mkErrorAppDs :: Id -- The error function
419 -> Type -- Type to which it should be applied
420 -> String -- The error message string to pass
423 mkErrorAppDs err_id ty msg
424 = getSrcLocDs `thenDs` \ src_loc ->
426 full_msg = showSDoc (hcat [ppr src_loc, text "|", text msg])
427 core_msg = Lit (MachStr (mkFastString (stringToUtf8 full_msg)))
429 returnDs (mkApps (Var err_id) [Type ty, core_msg])
433 *************************************************************
435 \subsection{Making literals}
437 %************************************************************************
440 mkCharExpr :: Int -> CoreExpr -- Returns C# c :: Int
441 mkIntExpr :: Integer -> CoreExpr -- Returns I# i :: Int
442 mkIntegerExpr :: Integer -> DsM CoreExpr -- Result :: Integer
443 mkStringLit :: String -> DsM CoreExpr -- Result :: String
444 mkStringLitFS :: FastString -> DsM CoreExpr -- Result :: String
446 mkIntExpr i = mkConApp intDataCon [mkIntLit i]
447 mkCharExpr c = mkConApp charDataCon [mkLit (MachChar c)]
450 | inIntRange i -- Small enough, so start from an Int
451 = returnDs (mkSmallIntegerLit i)
453 -- Special case for integral literals with a large magnitude:
454 -- They are transformed into an expression involving only smaller
455 -- integral literals. This improves constant folding.
457 | otherwise -- Big, so start from a string
458 = dsLookupGlobalId plusIntegerName `thenDs` \ plus_id ->
459 dsLookupGlobalId timesIntegerName `thenDs` \ times_id ->
461 plus a b = Var plus_id `App` a `App` b
462 times a b = Var times_id `App` a `App` b
464 -- Transform i into (x1 + (x2 + (x3 + (...) * b) * b) * b) with abs xi <= b
465 horner :: Integer -> Integer -> CoreExpr
466 horner b i | abs q <= 1 = if r == 0 || r == i
467 then mkSmallIntegerLit i
468 else mkSmallIntegerLit r `plus` mkSmallIntegerLit (i-r)
469 | r == 0 = horner b q `times` mkSmallIntegerLit b
470 | otherwise = mkSmallIntegerLit r `plus` (horner b q `times` mkSmallIntegerLit b)
472 (q,r) = i `quotRem` b
475 returnDs (horner tARGET_MAX_INT i)
477 mkSmallIntegerLit i = mkConApp smallIntegerDataCon [mkIntLit i]
479 mkStringLit str = mkStringLitFS (mkFastString str)
483 = returnDs (mkNilExpr charTy)
487 the_char = mkCharExpr (headIntFS str)
489 returnDs (mkConsExpr charTy the_char (mkNilExpr charTy))
491 | all safeChar int_chars
492 = dsLookupGlobalId unpackCStringName `thenDs` \ unpack_id ->
493 returnDs (App (Var unpack_id) (Lit (MachStr str)))
496 = dsLookupGlobalId unpackCStringUtf8Name `thenDs` \ unpack_id ->
497 returnDs (App (Var unpack_id) (Lit (MachStr (mkFastString (intsToUtf8 int_chars)))))
500 int_chars = unpackIntFS str
501 safeChar c = c >= 1 && c <= 0xFF
505 %************************************************************************
507 \subsection[mkSelectorBind]{Make a selector bind}
509 %************************************************************************
511 This is used in various places to do with lazy patterns.
512 For each binder $b$ in the pattern, we create a binding:
514 b = case v of pat' -> b'
516 where @pat'@ is @pat@ with each binder @b@ cloned into @b'@.
518 ToDo: making these bindings should really depend on whether there's
519 much work to be done per binding. If the pattern is complex, it
520 should be de-mangled once, into a tuple (and then selected from).
521 Otherwise the demangling can be in-line in the bindings (as here).
523 Boring! Boring! One error message per binder. The above ToDo is
524 even more helpful. Something very similar happens for pattern-bound
528 mkSelectorBinds :: TypecheckedPat -- The pattern
529 -> CoreExpr -- Expression to which the pattern is bound
530 -> DsM [(Id,CoreExpr)]
532 mkSelectorBinds (VarPat v) val_expr
533 = returnDs [(v, val_expr)]
535 mkSelectorBinds pat val_expr
536 | isSingleton binders || is_simple_pat pat
537 = -- Given p = e, where p binds x,y
538 -- we are going to make
539 -- v = p (where v is fresh)
540 -- x = case v of p -> x
541 -- y = case v of p -> x
544 -- NB: give it the type of *pattern* p, not the type of the *rhs* e.
545 -- This does not matter after desugaring, but there's a subtle
546 -- issue with implicit parameters. Consider
548 -- Then, ?i is given type {?i :: Int}, a SourceType, which is opaque
549 -- to the desugarer. (Why opaque? Because newtypes have to be. Why
550 -- does it get that type? So that when we abstract over it we get the
551 -- right top-level type (?i::Int) => ...)
553 -- So to get the type of 'v', use the pattern not the rhs. Often more
555 newSysLocalDs (hsPatType pat) `thenDs` \ val_var ->
557 -- For the error message we make one error-app, to avoid duplication.
558 -- But we need it at different types... so we use coerce for that
559 mkErrorAppDs iRREFUT_PAT_ERROR_ID
560 unitTy (showSDoc (ppr pat)) `thenDs` \ err_expr ->
561 newSysLocalDs unitTy `thenDs` \ err_var ->
562 mapDs (mk_bind val_var err_var) binders `thenDs` \ binds ->
563 returnDs ( (val_var, val_expr) :
564 (err_var, err_expr) :
569 = mkErrorAppDs iRREFUT_PAT_ERROR_ID
570 tuple_ty (showSDoc (ppr pat)) `thenDs` \ error_expr ->
571 matchSimply val_expr PatBindRhs pat local_tuple error_expr `thenDs` \ tuple_expr ->
572 newSysLocalDs tuple_ty `thenDs` \ tuple_var ->
575 = (binder, mkTupleSelector binders binder tuple_var (Var tuple_var))
577 returnDs ( (tuple_var, tuple_expr) : map mk_tup_bind binders )
579 binders = collectPatBinders pat
580 local_tuple = mkTupleExpr binders
581 tuple_ty = exprType local_tuple
583 mk_bind scrut_var err_var bndr_var
584 -- (mk_bind sv err_var) generates
585 -- bv = case sv of { pat -> bv; other -> coerce (type-of-bv) err_var }
586 -- Remember, pat binds bv
587 = matchSimply (Var scrut_var) PatBindRhs pat
588 (Var bndr_var) error_expr `thenDs` \ rhs_expr ->
589 returnDs (bndr_var, rhs_expr)
591 error_expr = mkCoerce (idType bndr_var) (Var err_var)
593 is_simple_pat (TuplePat ps Boxed) = all is_triv_pat ps
594 is_simple_pat (ConPatOut _ ps _ _ _) = all is_triv_pat (hsConArgs ps)
595 is_simple_pat (VarPat _) = True
596 is_simple_pat (ParPat p) = is_simple_pat p
597 is_simple_pat other = False
599 is_triv_pat (VarPat v) = True
600 is_triv_pat (WildPat _) = True
601 is_triv_pat (ParPat p) = is_triv_pat p
602 is_triv_pat other = False
606 %************************************************************************
610 %************************************************************************
612 @mkTupleExpr@ builds a tuple; the inverse to @mkTupleSelector@.
614 * If it has only one element, it is the identity function.
616 * If there are more elements than a big tuple can have, it nests
619 Nesting policy. Better a 2-tuple of 10-tuples (3 objects) than
620 a 10-tuple of 2-tuples (11 objects). So we want the leaves to be big.
623 mkTupleExpr :: [Id] -> CoreExpr
625 = mk_tuple_expr (chunkify (map Var ids))
627 mk_tuple_expr :: [[CoreExpr]] -> CoreExpr
628 -- Each sub-list is short enough to fit in a tuple
629 mk_tuple_expr [exprs] = mkCoreTup exprs
630 mk_tuple_expr exprs_s = mk_tuple_expr (chunkify (map mkCoreTup exprs_s))
633 chunkify :: [a] -> [[a]]
634 -- The sub-lists of the result all have length <= mAX_TUPLE_SIZE
635 -- But there may be more than mAX_TUPLE_SIZE sub-lists
637 | n_xs <= mAX_TUPLE_SIZE = {- pprTrace "Small" (ppr n_xs) -} [xs]
638 | otherwise = {- pprTrace "Big" (ppr n_xs) -} (split xs)
642 split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
646 @mkTupleSelector@ builds a selector which scrutises the given
647 expression and extracts the one name from the list given.
648 If you want the no-shadowing rule to apply, the caller
649 is responsible for making sure that none of these names
652 If there is just one id in the ``tuple'', then the selector is
655 If it's big, it does nesting
656 mkTupleSelector [a,b,c,d] b v e
658 (p,q) -> case p of p {
660 We use 'tpl' vars for the p,q, since shadowing does not matter.
662 In fact, it's more convenient to generate it innermost first, getting
669 mkTupleSelector :: [Id] -- The tuple args
670 -> Id -- The selected one
671 -> Id -- A variable of the same type as the scrutinee
672 -> CoreExpr -- Scrutinee
675 mkTupleSelector vars the_var scrut_var scrut
676 = mk_tup_sel (chunkify vars) the_var
678 mk_tup_sel [vars] the_var = mkCoreSel vars the_var scrut_var scrut
679 mk_tup_sel vars_s the_var = mkCoreSel group the_var tpl_v $
680 mk_tup_sel (chunkify tpl_vs) tpl_v
682 tpl_tys = [mkCoreTupTy (map idType gp) | gp <- vars_s]
683 tpl_vs = mkTemplateLocals tpl_tys
684 [(tpl_v, group)] = [(tpl,gp) | (tpl,gp) <- zipEqual "mkTupleSelector" tpl_vs vars_s,
689 %************************************************************************
691 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
693 %************************************************************************
695 Call the constructor Ids when building explicit lists, so that they
696 interact well with rules.
699 mkNilExpr :: Type -> CoreExpr
700 mkNilExpr ty = mkConApp nilDataCon [Type ty]
702 mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
703 mkConsExpr ty hd tl = mkConApp consDataCon [Type ty, hd, tl]
705 mkListExpr :: Type -> [CoreExpr] -> CoreExpr
706 mkListExpr ty xs = foldr (mkConsExpr ty) (mkNilExpr ty) xs
709 -- The next three functions make tuple types, constructors and selectors,
710 -- with the rule that a 1-tuple is represented by the thing itselg
711 mkCoreTupTy :: [Type] -> Type
712 mkCoreTupTy [ty] = ty
713 mkCoreTupTy tys = mkTupleTy Boxed (length tys) tys
715 mkCoreTup :: [CoreExpr] -> CoreExpr
716 -- Builds exactly the specified tuple.
717 -- No fancy business for big tuples
718 mkCoreTup [] = Var unitDataConId
720 mkCoreTup cs = mkConApp (tupleCon Boxed (length cs))
721 (map (Type . exprType) cs ++ cs)
723 mkCoreSel :: [Id] -- The tuple args
724 -> Id -- The selected one
725 -> Id -- A variable of the same type as the scrutinee
726 -> CoreExpr -- Scrutinee
728 -- mkCoreSel [x,y,z] x v e
729 -- ===> case e of v { (x,y,z) -> x
730 mkCoreSel [var] should_be_the_same_var scrut_var scrut
731 = ASSERT(var == should_be_the_same_var)
734 mkCoreSel vars the_var scrut_var scrut
735 = ASSERT( notNull vars )
737 [(DataAlt (tupleCon Boxed (length vars)), vars, Var the_var)]
741 %************************************************************************
743 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
745 %************************************************************************
747 Generally, we handle pattern matching failure like this: let-bind a
748 fail-variable, and use that variable if the thing fails:
750 let fail.33 = error "Help"
761 If the case can't fail, then there'll be no mention of @fail.33@, and the
762 simplifier will later discard it.
765 If it can fail in only one way, then the simplifier will inline it.
768 Only if it is used more than once will the let-binding remain.
771 There's a problem when the result of the case expression is of
772 unboxed type. Then the type of @fail.33@ is unboxed too, and
773 there is every chance that someone will change the let into a case:
779 which is of course utterly wrong. Rather than drop the condition that
780 only boxed types can be let-bound, we just turn the fail into a function
781 for the primitive case:
783 let fail.33 :: Void -> Int#
784 fail.33 = \_ -> error "Help"
793 Now @fail.33@ is a function, so it can be let-bound.
796 mkFailurePair :: CoreExpr -- Result type of the whole case expression
797 -> DsM (CoreBind, -- Binds the newly-created fail variable
798 -- to either the expression or \ _ -> expression
799 CoreExpr) -- Either the fail variable, or fail variable
800 -- applied to unit tuple
803 = newFailLocalDs (unitTy `mkFunTy` ty) `thenDs` \ fail_fun_var ->
804 newSysLocalDs unitTy `thenDs` \ fail_fun_arg ->
805 returnDs (NonRec fail_fun_var (Lam fail_fun_arg expr),
806 App (Var fail_fun_var) (Var unitDataConId))
809 = newFailLocalDs ty `thenDs` \ fail_var ->
810 returnDs (NonRec fail_var expr, Var fail_var)