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 mkTupleType, mkTupleCase, mkBigCoreTup,
29 mkCoreTup, mkCoreTupTy,
31 dsReboundNames, lookupReboundName,
33 selectMatchVarL, selectMatchVar
36 #include "HsVersions.h"
38 import {-# SOURCE #-} Match ( matchSimply )
39 import {-# SOURCE #-} DsExpr( dsExpr )
42 import TcHsSyn ( hsPatType )
44 import Constants ( mAX_TUPLE_SIZE )
47 import CoreUtils ( exprType, mkIfThenElse, mkCoerce, bindNonRec )
48 import MkId ( iRREFUT_PAT_ERROR_ID, mkReboxingAlt, mkNewTypeBody )
49 import Id ( idType, Id, mkWildId, mkTemplateLocals, mkSysLocal )
51 import Literal ( Literal(..), inIntRange, tARGET_MAX_INT )
52 import TyCon ( isNewTyCon, tyConDataCons )
53 import DataCon ( DataCon, dataConSourceArity )
54 import Type ( mkFunTy, isUnLiftedType, Type, splitTyConApp )
55 import TcType ( tcTyConAppTyCon, isIntTy, isFloatTy, isDoubleTy )
56 import TysPrim ( intPrimTy )
57 import TysWiredIn ( nilDataCon, consDataCon,
59 unitDataConId, unitTy,
64 stringTy, isPArrFakeCon )
65 import BasicTypes ( Boxity(..) )
66 import UniqSet ( mkUniqSet, minusUniqSet, isEmptyUniqSet, UniqSet )
67 import UniqSupply ( splitUniqSupply, uniqFromSupply, uniqsFromSupply )
68 import PrelNames ( unpackCStringName, unpackCStringUtf8Name,
69 plusIntegerName, timesIntegerName, smallIntegerDataConName,
70 lengthPName, indexPName )
72 import UnicodeUtil ( intsToUtf8, stringToUtf8 )
73 import SrcLoc ( Located(..), unLoc, noLoc )
74 import Util ( isSingleton, notNull, zipEqual )
75 import ListSetOps ( assocDefault )
81 %************************************************************************
85 %************************************************************************
88 dsReboundNames :: ReboundNames Id
89 -> DsM ([CoreBind], -- Auxiliary bindings
90 [(Name,Id)]) -- Maps the standard name to its value
92 dsReboundNames rebound_ids
93 = mapAndUnzipDs mk_bind rebound_ids `thenDs` \ (binds_s, prs) ->
94 return (concat binds_s, prs)
96 -- The cheapo special case can happen when we
97 -- make an intermediate HsDo when desugaring a RecStmt
98 mk_bind (std_name, HsVar id) = return ([], (std_name, id))
99 mk_bind (std_name, expr)
100 = dsExpr expr `thenDs` \ rhs ->
101 newSysLocalDs (exprType rhs) `thenDs` \ id ->
102 return ([NonRec id rhs], (std_name, id))
104 lookupReboundName :: [(Name,Id)] -> Name -> CoreExpr
105 lookupReboundName prs std_name
106 = Var (assocDefault (mk_panic std_name) prs std_name)
108 mk_panic std_name = pprPanic "dsReboundNames" (ptext SLIT("Not found:") <+> ppr std_name)
112 %************************************************************************
114 \subsection{Tidying lit pats}
116 %************************************************************************
119 tidyLitPat :: HsLit -> LPat Id -> LPat Id
120 tidyLitPat (HsChar c) pat = mkCharLitPat c
121 tidyLitPat lit pat = pat
123 tidyNPat :: HsLit -> Type -> LPat Id -> LPat Id
124 tidyNPat (HsString s) _ pat
125 | lengthFS s <= 1 -- Short string literals only
126 = foldr (\c pat -> mkPrefixConPat consDataCon [mkCharLitPat c,pat] stringTy)
127 (mkNilPat stringTy) (unpackFS s)
128 -- The stringTy is the type of the whole pattern, not
129 -- the type to instantiate (:) or [] with!
132 tidyNPat lit lit_ty default_pat
133 | isIntTy lit_ty = mkPrefixConPat intDataCon [noLoc $ LitPat (mk_int lit)] lit_ty
134 | isFloatTy lit_ty = mkPrefixConPat floatDataCon [noLoc $ LitPat (mk_float lit)] lit_ty
135 | isDoubleTy lit_ty = mkPrefixConPat doubleDataCon [noLoc $ LitPat (mk_double lit)] lit_ty
136 | otherwise = default_pat
139 mk_int (HsInteger i _) = HsIntPrim i
141 mk_float (HsInteger i _) = HsFloatPrim (fromInteger i)
142 mk_float (HsRat f _) = HsFloatPrim f
144 mk_double (HsInteger i _) = HsDoublePrim (fromInteger i)
145 mk_double (HsRat f _) = HsDoublePrim f
149 %************************************************************************
151 \subsection{Building lets}
153 %************************************************************************
155 Use case, not let for unlifted types. The simplifier will turn some
159 mkDsLet :: CoreBind -> CoreExpr -> CoreExpr
160 mkDsLet (NonRec bndr rhs) body
161 | isUnLiftedType (idType bndr) = Case rhs bndr [(DEFAULT,[],body)]
165 mkDsLets :: [CoreBind] -> CoreExpr -> CoreExpr
166 mkDsLets binds body = foldr mkDsLet body binds
170 %************************************************************************
172 \subsection{ Selecting match variables}
174 %************************************************************************
176 We're about to match against some patterns. We want to make some
177 @Ids@ to use as match variables. If a pattern has an @Id@ readily at
178 hand, which should indeed be bound to the pattern as a whole, then use it;
179 otherwise, make one up.
182 selectMatchVarL :: LPat Id -> DsM Id
183 selectMatchVarL pat = selectMatchVar (unLoc pat)
185 selectMatchVar (VarPat var) = returnDs var
186 selectMatchVar (AsPat var pat) = returnDs (unLoc var)
187 selectMatchVar (LazyPat pat) = selectMatchVarL pat
188 selectMatchVar other_pat = newSysLocalDs (hsPatType (noLoc other_pat))
189 -- OK, better make up one...
193 %************************************************************************
195 %* type synonym EquationInfo and access functions for its pieces *
197 %************************************************************************
198 \subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
200 The ``equation info'' used by @match@ is relatively complicated and
201 worthy of a type synonym and a few handy functions.
206 type EqnSet = UniqSet EqnNo
210 EqnNo -- The number of the equation
212 DsMatchContext -- The context info is used when producing warnings
213 -- about shadowed patterns. It's the context
214 -- of the *first* thing matched in this group.
215 -- Should perhaps be a list of them all!
217 [Pat Id] -- The patterns for an eqn
219 MatchResult -- Encapsulates the guards and bindings
225 CanItFail -- Tells whether the failure expression is used
226 (CoreExpr -> DsM CoreExpr)
227 -- Takes a expression to plug in at the
228 -- failure point(s). The expression should
231 data CanItFail = CanFail | CantFail
233 orFail CantFail CantFail = CantFail
237 Functions on MatchResults
240 cantFailMatchResult :: CoreExpr -> MatchResult
241 cantFailMatchResult expr = MatchResult CantFail (\ ignore -> returnDs expr)
243 extractMatchResult :: MatchResult -> CoreExpr -> DsM CoreExpr
244 extractMatchResult (MatchResult CantFail match_fn) fail_expr
245 = match_fn (error "It can't fail!")
247 extractMatchResult (MatchResult CanFail match_fn) fail_expr
248 = mkFailurePair fail_expr `thenDs` \ (fail_bind, if_it_fails) ->
249 match_fn if_it_fails `thenDs` \ body ->
250 returnDs (mkDsLet fail_bind body)
253 combineMatchResults :: MatchResult -> MatchResult -> MatchResult
254 combineMatchResults (MatchResult CanFail body_fn1)
255 (MatchResult can_it_fail2 body_fn2)
256 = MatchResult can_it_fail2 body_fn
258 body_fn fail = body_fn2 fail `thenDs` \ body2 ->
259 mkFailurePair body2 `thenDs` \ (fail_bind, duplicatable_expr) ->
260 body_fn1 duplicatable_expr `thenDs` \ body1 ->
261 returnDs (Let fail_bind body1)
263 combineMatchResults match_result1@(MatchResult CantFail body_fn1) match_result2
267 adjustMatchResult :: (CoreExpr -> CoreExpr) -> MatchResult -> MatchResult
268 adjustMatchResult encl_fn (MatchResult can_it_fail body_fn)
269 = MatchResult can_it_fail (\fail -> body_fn fail `thenDs` \ body ->
270 returnDs (encl_fn body))
272 adjustMatchResultDs :: (CoreExpr -> DsM CoreExpr) -> MatchResult -> MatchResult
273 adjustMatchResultDs encl_fn (MatchResult can_it_fail body_fn)
274 = MatchResult can_it_fail (\fail -> body_fn fail `thenDs` \ body ->
278 mkCoLetsMatchResult :: [CoreBind] -> MatchResult -> MatchResult
279 mkCoLetsMatchResult binds match_result
280 = adjustMatchResult (mkDsLets binds) match_result
283 mkGuardedMatchResult :: CoreExpr -> MatchResult -> MatchResult
284 mkGuardedMatchResult pred_expr (MatchResult can_it_fail body_fn)
285 = MatchResult CanFail (\fail -> body_fn fail `thenDs` \ body ->
286 returnDs (mkIfThenElse pred_expr body fail))
288 mkCoPrimCaseMatchResult :: Id -- Scrutinee
289 -> [(Literal, MatchResult)] -- Alternatives
291 mkCoPrimCaseMatchResult var match_alts
292 = MatchResult CanFail mk_case
295 = mappM (mk_alt fail) match_alts `thenDs` \ alts ->
296 returnDs (Case (Var var) var ((DEFAULT, [], fail) : alts))
298 mk_alt fail (lit, MatchResult _ body_fn) = body_fn fail `thenDs` \ body ->
299 returnDs (LitAlt lit, [], body)
302 mkCoAlgCaseMatchResult :: Id -- Scrutinee
303 -> [(DataCon, [CoreBndr], MatchResult)] -- Alternatives
306 mkCoAlgCaseMatchResult var match_alts
307 | isNewTyCon tycon -- Newtype case; use a let
308 = ASSERT( null (tail match_alts) && null (tail arg_ids) )
309 mkCoLetsMatchResult [NonRec arg_id newtype_rhs] match_result
311 | isPArrFakeAlts match_alts -- Sugared parallel array; use a literal case
312 = MatchResult CanFail mk_parrCase
314 | otherwise -- Datatype case; use a case
315 = MatchResult fail_flag mk_case
318 scrut_ty = idType var
319 tycon = tcTyConAppTyCon scrut_ty -- Newtypes must be opaque here
322 (_, arg_ids, match_result) = head match_alts
323 arg_id = head arg_ids
324 newtype_rhs = mkNewTypeBody tycon (idType arg_id) (Var var)
326 -- Stuff for data types
327 data_cons = tyConDataCons tycon
328 match_results = [match_result | (_,_,match_result) <- match_alts]
330 fail_flag | exhaustive_case
331 = foldr1 orFail [can_it_fail | MatchResult can_it_fail _ <- match_results]
335 wild_var = mkWildId (idType var)
336 mk_case fail = mappM (mk_alt fail) match_alts `thenDs` \ alts ->
337 returnDs (Case (Var var) wild_var (mk_default fail ++ alts))
339 mk_alt fail (con, args, MatchResult _ body_fn)
340 = body_fn fail `thenDs` \ body ->
341 newUniqueSupply `thenDs` \ us ->
342 returnDs (mkReboxingAlt (uniqsFromSupply us) con args body)
344 mk_default fail | exhaustive_case = []
345 | otherwise = [(DEFAULT, [], fail)]
347 un_mentioned_constructors
348 = mkUniqSet data_cons `minusUniqSet` mkUniqSet [ con | (con, _, _) <- match_alts]
349 exhaustive_case = isEmptyUniqSet un_mentioned_constructors
351 -- Stuff for parallel arrays
353 -- * the following is to desugar cases over fake constructors for
354 -- parallel arrays, which are introduced by `tidy1' in the `PArrPat'
357 -- Concerning `isPArrFakeAlts':
359 -- * it is *not* sufficient to just check the type of the type
360 -- constructor, as we have to be careful not to confuse the real
361 -- representation of parallel arrays with the fake constructors;
362 -- moreover, a list of alternatives must not mix fake and real
363 -- constructors (this is checked earlier on)
365 -- FIXME: We actually go through the whole list and make sure that
366 -- either all or none of the constructors are fake parallel
367 -- array constructors. This is to spot equations that mix fake
368 -- constructors with the real representation defined in
369 -- `PrelPArr'. It would be nicer to spot this situation
370 -- earlier and raise a proper error message, but it can really
371 -- only happen in `PrelPArr' anyway.
373 isPArrFakeAlts [(dcon, _, _)] = isPArrFakeCon dcon
374 isPArrFakeAlts ((dcon, _, _):alts) =
375 case (isPArrFakeCon dcon, isPArrFakeAlts alts) of
376 (True , True ) -> True
377 (False, False) -> False
379 panic "DsUtils: You may not mix `[:...:]' with `PArr' patterns"
382 dsLookupGlobalId lengthPName `thenDs` \lengthP ->
383 unboxAlt `thenDs` \alt ->
384 returnDs (Case (len lengthP) (mkWildId intTy) [alt])
386 elemTy = case splitTyConApp (idType var) of
387 (_, [elemTy]) -> elemTy
389 panicMsg = "DsUtils.mkCoAlgCaseMatchResult: not a parallel array?"
390 len lengthP = mkApps (Var lengthP) [Type elemTy, Var var]
393 newSysLocalDs intPrimTy `thenDs` \l ->
394 dsLookupGlobalId indexPName `thenDs` \indexP ->
395 mappM (mkAlt indexP) match_alts `thenDs` \alts ->
396 returnDs (DataAlt intDataCon, [l], (Case (Var l) wild (dft : alts)))
398 wild = mkWildId intPrimTy
399 dft = (DEFAULT, [], fail)
401 -- each alternative matches one array length (corresponding to one
402 -- fake array constructor), so the match is on a literal; each
403 -- alternative's body is extended by a local binding for each
404 -- constructor argument, which are bound to array elements starting
407 mkAlt indexP (con, args, MatchResult _ bodyFun) =
408 bodyFun fail `thenDs` \body ->
409 returnDs (LitAlt lit, [], mkDsLets binds body)
411 lit = MachInt $ toInteger (dataConSourceArity con)
412 binds = [NonRec arg (indexExpr i) | (i, arg) <- zip [1..] args]
414 indexExpr i = mkApps (Var indexP) [Type elemTy, Var var, mkIntExpr i]
418 %************************************************************************
420 \subsection{Desugarer's versions of some Core functions}
422 %************************************************************************
425 mkErrorAppDs :: Id -- The error function
426 -> Type -- Type to which it should be applied
427 -> String -- The error message string to pass
430 mkErrorAppDs err_id ty msg
431 = getSrcSpanDs `thenDs` \ src_loc ->
433 full_msg = showSDoc (hcat [ppr src_loc, text "|", text msg])
434 core_msg = Lit (MachStr (mkFastString (stringToUtf8 full_msg)))
436 returnDs (mkApps (Var err_id) [Type ty, core_msg])
440 *************************************************************
442 \subsection{Making literals}
444 %************************************************************************
447 mkCharExpr :: Char -> CoreExpr -- Returns C# c :: Int
448 mkIntExpr :: Integer -> CoreExpr -- Returns I# i :: Int
449 mkIntegerExpr :: Integer -> DsM CoreExpr -- Result :: Integer
450 mkStringLit :: String -> DsM CoreExpr -- Result :: String
451 mkStringLitFS :: FastString -> DsM CoreExpr -- Result :: String
453 mkIntExpr i = mkConApp intDataCon [mkIntLit i]
454 mkCharExpr c = mkConApp charDataCon [mkLit (MachChar c)]
457 | inIntRange i -- Small enough, so start from an Int
458 = dsLookupDataCon smallIntegerDataConName `thenDs` \ integer_dc ->
459 returnDs (mkSmallIntegerLit integer_dc i)
461 -- Special case for integral literals with a large magnitude:
462 -- They are transformed into an expression involving only smaller
463 -- integral literals. This improves constant folding.
465 | otherwise -- Big, so start from a string
466 = dsLookupGlobalId plusIntegerName `thenDs` \ plus_id ->
467 dsLookupGlobalId timesIntegerName `thenDs` \ times_id ->
468 dsLookupDataCon smallIntegerDataConName `thenDs` \ integer_dc ->
470 lit i = mkSmallIntegerLit integer_dc i
471 plus a b = Var plus_id `App` a `App` b
472 times a b = Var times_id `App` a `App` b
474 -- Transform i into (x1 + (x2 + (x3 + (...) * b) * b) * b) with abs xi <= b
475 horner :: Integer -> Integer -> CoreExpr
476 horner b i | abs q <= 1 = if r == 0 || r == i
478 else lit r `plus` lit (i-r)
479 | r == 0 = horner b q `times` lit b
480 | otherwise = lit r `plus` (horner b q `times` lit b)
482 (q,r) = i `quotRem` b
485 returnDs (horner tARGET_MAX_INT i)
487 mkSmallIntegerLit small_integer_data_con i = mkConApp small_integer_data_con [mkIntLit i]
489 mkStringLit str = mkStringLitFS (mkFastString str)
493 = returnDs (mkNilExpr charTy)
497 the_char = mkCharExpr (headFS str)
499 returnDs (mkConsExpr charTy the_char (mkNilExpr charTy))
501 | all safeChar int_chars
502 = dsLookupGlobalId unpackCStringName `thenDs` \ unpack_id ->
503 returnDs (App (Var unpack_id) (Lit (MachStr str)))
506 = dsLookupGlobalId unpackCStringUtf8Name `thenDs` \ unpack_id ->
507 returnDs (App (Var unpack_id) (Lit (MachStr (mkFastString (intsToUtf8 int_chars)))))
510 int_chars = unpackIntFS str
511 safeChar c = c >= 1 && c <= 0xFF
515 %************************************************************************
517 \subsection[mkSelectorBind]{Make a selector bind}
519 %************************************************************************
521 This is used in various places to do with lazy patterns.
522 For each binder $b$ in the pattern, we create a binding:
524 b = case v of pat' -> b'
526 where @pat'@ is @pat@ with each binder @b@ cloned into @b'@.
528 ToDo: making these bindings should really depend on whether there's
529 much work to be done per binding. If the pattern is complex, it
530 should be de-mangled once, into a tuple (and then selected from).
531 Otherwise the demangling can be in-line in the bindings (as here).
533 Boring! Boring! One error message per binder. The above ToDo is
534 even more helpful. Something very similar happens for pattern-bound
538 mkSelectorBinds :: LPat Id -- The pattern
539 -> CoreExpr -- Expression to which the pattern is bound
540 -> DsM [(Id,CoreExpr)]
542 mkSelectorBinds (L _ (VarPat v)) val_expr
543 = returnDs [(v, val_expr)]
545 mkSelectorBinds pat val_expr
546 | isSingleton binders || is_simple_lpat pat
547 = -- Given p = e, where p binds x,y
548 -- we are going to make
549 -- v = p (where v is fresh)
550 -- x = case v of p -> x
551 -- y = case v of p -> x
554 -- NB: give it the type of *pattern* p, not the type of the *rhs* e.
555 -- This does not matter after desugaring, but there's a subtle
556 -- issue with implicit parameters. Consider
558 -- Then, ?i is given type {?i :: Int}, a PredType, which is opaque
559 -- to the desugarer. (Why opaque? Because newtypes have to be. Why
560 -- does it get that type? So that when we abstract over it we get the
561 -- right top-level type (?i::Int) => ...)
563 -- So to get the type of 'v', use the pattern not the rhs. Often more
565 newSysLocalDs (hsPatType pat) `thenDs` \ val_var ->
567 -- For the error message we make one error-app, to avoid duplication.
568 -- But we need it at different types... so we use coerce for that
569 mkErrorAppDs iRREFUT_PAT_ERROR_ID
570 unitTy (showSDoc (ppr pat)) `thenDs` \ err_expr ->
571 newSysLocalDs unitTy `thenDs` \ err_var ->
572 mappM (mk_bind val_var err_var) binders `thenDs` \ binds ->
573 returnDs ( (val_var, val_expr) :
574 (err_var, err_expr) :
579 = mkErrorAppDs iRREFUT_PAT_ERROR_ID
580 tuple_ty (showSDoc (ppr pat)) `thenDs` \ error_expr ->
581 matchSimply val_expr PatBindRhs pat local_tuple error_expr `thenDs` \ tuple_expr ->
582 newSysLocalDs tuple_ty `thenDs` \ tuple_var ->
585 = (binder, mkTupleSelector binders binder tuple_var (Var tuple_var))
587 returnDs ( (tuple_var, tuple_expr) : map mk_tup_bind binders )
589 binders = collectPatBinders pat
590 local_tuple = mkTupleExpr binders
591 tuple_ty = exprType local_tuple
593 mk_bind scrut_var err_var bndr_var
594 -- (mk_bind sv err_var) generates
595 -- bv = case sv of { pat -> bv; other -> coerce (type-of-bv) err_var }
596 -- Remember, pat binds bv
597 = matchSimply (Var scrut_var) PatBindRhs pat
598 (Var bndr_var) error_expr `thenDs` \ rhs_expr ->
599 returnDs (bndr_var, rhs_expr)
601 error_expr = mkCoerce (idType bndr_var) (Var err_var)
603 is_simple_lpat p = is_simple_pat (unLoc p)
605 is_simple_pat (TuplePat ps Boxed) = all is_triv_lpat ps
606 is_simple_pat (ConPatOut _ ps _ _ _) = all is_triv_lpat (hsConArgs ps)
607 is_simple_pat (VarPat _) = True
608 is_simple_pat (ParPat p) = is_simple_lpat p
609 is_simple_pat other = False
611 is_triv_lpat p = is_triv_pat (unLoc p)
613 is_triv_pat (VarPat v) = True
614 is_triv_pat (WildPat _) = True
615 is_triv_pat (ParPat p) = is_triv_lpat p
616 is_triv_pat other = False
620 %************************************************************************
624 %************************************************************************
626 @mkTupleExpr@ builds a tuple; the inverse to @mkTupleSelector@.
628 * If it has only one element, it is the identity function.
630 * If there are more elements than a big tuple can have, it nests
633 Nesting policy. Better a 2-tuple of 10-tuples (3 objects) than
634 a 10-tuple of 2-tuples (11 objects). So we want the leaves to be big.
637 mkTupleExpr :: [Id] -> CoreExpr
638 mkTupleExpr ids = mkBigCoreTup (map Var ids)
640 -- corresponding type
641 mkTupleType :: [Id] -> Type
642 mkTupleType ids = mkBigTuple mkCoreTupTy (map idType ids)
644 mkBigCoreTup :: [CoreExpr] -> CoreExpr
645 mkBigCoreTup = mkBigTuple mkCoreTup
647 mkBigTuple :: ([a] -> a) -> [a] -> a
648 mkBigTuple small_tuple as = mk_big_tuple (chunkify as)
650 -- Each sub-list is short enough to fit in a tuple
651 mk_big_tuple [as] = small_tuple as
652 mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s))
654 chunkify :: [a] -> [[a]]
655 -- The sub-lists of the result all have length <= mAX_TUPLE_SIZE
656 -- But there may be more than mAX_TUPLE_SIZE sub-lists
658 | n_xs <= mAX_TUPLE_SIZE = {- pprTrace "Small" (ppr n_xs) -} [xs]
659 | otherwise = {- pprTrace "Big" (ppr n_xs) -} (split xs)
663 split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
667 @mkTupleSelector@ builds a selector which scrutises the given
668 expression and extracts the one name from the list given.
669 If you want the no-shadowing rule to apply, the caller
670 is responsible for making sure that none of these names
673 If there is just one id in the ``tuple'', then the selector is
676 If it's big, it does nesting
677 mkTupleSelector [a,b,c,d] b v e
679 (p,q) -> case p of p {
681 We use 'tpl' vars for the p,q, since shadowing does not matter.
683 In fact, it's more convenient to generate it innermost first, getting
690 mkTupleSelector :: [Id] -- The tuple args
691 -> Id -- The selected one
692 -> Id -- A variable of the same type as the scrutinee
693 -> CoreExpr -- Scrutinee
696 mkTupleSelector vars the_var scrut_var scrut
697 = mk_tup_sel (chunkify vars) the_var
699 mk_tup_sel [vars] the_var = mkCoreSel vars the_var scrut_var scrut
700 mk_tup_sel vars_s the_var = mkCoreSel group the_var tpl_v $
701 mk_tup_sel (chunkify tpl_vs) tpl_v
703 tpl_tys = [mkCoreTupTy (map idType gp) | gp <- vars_s]
704 tpl_vs = mkTemplateLocals tpl_tys
705 [(tpl_v, group)] = [(tpl,gp) | (tpl,gp) <- zipEqual "mkTupleSelector" tpl_vs vars_s,
709 A generalization of @mkTupleSelector@, allowing the body
710 of the case to be an arbitrary expression.
712 If the tuple is big, it is nested:
714 mkTupleCase uniqs [a,b,c,d] body v e
715 = case e of v { (p,q) ->
716 case p of p { (a,b) ->
717 case q of q { (c,d) ->
720 To avoid shadowing, we use uniqs to invent new variables p,q.
722 ToDo: eliminate cases where none of the variables are needed.
726 :: UniqSupply -- for inventing names of intermediate variables
727 -> [Id] -- the tuple args
728 -> CoreExpr -- body of the case
729 -> Id -- a variable of the same type as the scrutinee
730 -> CoreExpr -- scrutinee
733 mkTupleCase uniqs vars body scrut_var scrut
734 = mk_tuple_case uniqs (chunkify vars) body
736 mk_tuple_case us [vars] body
737 = mkSmallTupleCase vars body scrut_var scrut
738 mk_tuple_case us vars_s body
740 (us', vars', body') = foldr one_tuple_case (us, [], body) vars_s
742 mk_tuple_case us' (chunkify vars') body'
743 one_tuple_case chunk_vars (us, vs, body)
745 (us1, us2) = splitUniqSupply us
746 scrut_var = mkSysLocal FSLIT("ds") (uniqFromSupply us1)
747 (mkCoreTupTy (map idType chunk_vars))
748 body' = mkSmallTupleCase chunk_vars body scrut_var (Var scrut_var)
749 in (us2, scrut_var:vs, body')
752 The same, but with a tuple small enough not to need nesting.
756 :: [Id] -- the tuple args
757 -> CoreExpr -- body of the case
758 -> Id -- a variable of the same type as the scrutinee
759 -> CoreExpr -- scrutinee
762 mkSmallTupleCase [var] body _scrut_var scrut
763 = bindNonRec var scrut body
764 mkSmallTupleCase vars body scrut_var scrut
765 = Case scrut scrut_var [(DataAlt (tupleCon Boxed (length vars)), vars, body)]
768 %************************************************************************
770 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
772 %************************************************************************
774 Call the constructor Ids when building explicit lists, so that they
775 interact well with rules.
778 mkNilExpr :: Type -> CoreExpr
779 mkNilExpr ty = mkConApp nilDataCon [Type ty]
781 mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
782 mkConsExpr ty hd tl = mkConApp consDataCon [Type ty, hd, tl]
784 mkListExpr :: Type -> [CoreExpr] -> CoreExpr
785 mkListExpr ty xs = foldr (mkConsExpr ty) (mkNilExpr ty) xs
788 -- The next three functions make tuple types, constructors and selectors,
789 -- with the rule that a 1-tuple is represented by the thing itselg
790 mkCoreTupTy :: [Type] -> Type
791 mkCoreTupTy [ty] = ty
792 mkCoreTupTy tys = mkTupleTy Boxed (length tys) tys
794 mkCoreTup :: [CoreExpr] -> CoreExpr
795 -- Builds exactly the specified tuple.
796 -- No fancy business for big tuples
797 mkCoreTup [] = Var unitDataConId
799 mkCoreTup cs = mkConApp (tupleCon Boxed (length cs))
800 (map (Type . exprType) cs ++ cs)
802 mkCoreSel :: [Id] -- The tuple args
803 -> Id -- The selected one
804 -> Id -- A variable of the same type as the scrutinee
805 -> CoreExpr -- Scrutinee
807 -- mkCoreSel [x,y,z] x v e
808 -- ===> case e of v { (x,y,z) -> x
809 mkCoreSel [var] should_be_the_same_var scrut_var scrut
810 = ASSERT(var == should_be_the_same_var)
813 mkCoreSel vars the_var scrut_var scrut
814 = ASSERT( notNull vars )
816 [(DataAlt (tupleCon Boxed (length vars)), vars, Var the_var)]
820 %************************************************************************
822 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
824 %************************************************************************
826 Generally, we handle pattern matching failure like this: let-bind a
827 fail-variable, and use that variable if the thing fails:
829 let fail.33 = error "Help"
840 If the case can't fail, then there'll be no mention of @fail.33@, and the
841 simplifier will later discard it.
844 If it can fail in only one way, then the simplifier will inline it.
847 Only if it is used more than once will the let-binding remain.
850 There's a problem when the result of the case expression is of
851 unboxed type. Then the type of @fail.33@ is unboxed too, and
852 there is every chance that someone will change the let into a case:
858 which is of course utterly wrong. Rather than drop the condition that
859 only boxed types can be let-bound, we just turn the fail into a function
860 for the primitive case:
862 let fail.33 :: Void -> Int#
863 fail.33 = \_ -> error "Help"
872 Now @fail.33@ is a function, so it can be let-bound.
875 mkFailurePair :: CoreExpr -- Result type of the whole case expression
876 -> DsM (CoreBind, -- Binds the newly-created fail variable
877 -- to either the expression or \ _ -> expression
878 CoreExpr) -- Either the fail variable, or fail variable
879 -- applied to unit tuple
882 = newFailLocalDs (unitTy `mkFunTy` ty) `thenDs` \ fail_fun_var ->
883 newSysLocalDs unitTy `thenDs` \ fail_fun_arg ->
884 returnDs (NonRec fail_fun_var (Lam fail_fun_arg expr),
885 App (Var fail_fun_var) (Var unitDataConId))
888 = newFailLocalDs ty `thenDs` \ fail_var ->
889 returnDs (NonRec fail_var expr, Var fail_var)