[project @ 2003-07-15 13:33:24 by ross]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsUtils.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[DsUtils]{Utilities for desugaring}
5
6 This module exports some utility functions of no great interest.
7
8 \begin{code}
9 module DsUtils (
10         CanItFail(..), EquationInfo(..), MatchResult(..),
11         EqnNo, EqnSet,
12
13         tidyLitPat, tidyNPat,
14
15         mkDsLet, mkDsLets,
16
17         cantFailMatchResult, extractMatchResult,
18         combineMatchResults, 
19         adjustMatchResult, adjustMatchResultDs,
20         mkCoLetsMatchResult, mkGuardedMatchResult, 
21         mkCoPrimCaseMatchResult, mkCoAlgCaseMatchResult,
22
23         mkErrorAppDs, mkNilExpr, mkConsExpr, mkListExpr,
24         mkIntExpr, mkCharExpr,
25         mkStringLit, mkStringLitFS, mkIntegerExpr, 
26
27         mkSelectorBinds, mkTupleExpr, mkTupleSelector, 
28         mkTupleType, mkTupleCase, mkBigCoreTup,
29         mkCoreTup, mkCoreSel, mkCoreTupTy,
30         
31         dsReboundNames, lookupReboundName,
32
33         selectMatchVar
34     ) where
35
36 #include "HsVersions.h"
37
38 import {-# SOURCE #-}   Match ( matchSimply )
39 import {-# SOURCE #-}   DsExpr( dsExpr )
40
41 import HsSyn
42 import TcHsSyn          ( TypecheckedPat, hsPatType )
43 import CoreSyn
44 import Constants        ( mAX_TUPLE_SIZE )
45 import DsMonad
46
47 import CoreUtils        ( exprType, mkIfThenElse, mkCoerce, bindNonRec )
48 import MkId             ( iRREFUT_PAT_ERROR_ID, mkReboxingAlt, mkNewTypeBody )
49 import Id               ( idType, Id, mkWildId, mkTemplateLocals, mkSysLocal )
50 import Name             ( Name )
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, 
58                           tupleCon, mkTupleTy,
59                           unitDataConId, unitTy,
60                           charTy, charDataCon, 
61                           intTy, intDataCon, smallIntegerDataCon, 
62                           floatDataCon, 
63                           doubleDataCon,
64                           stringTy, isPArrFakeCon )
65 import BasicTypes       ( Boxity(..) )
66 import UniqSet          ( mkUniqSet, minusUniqSet, isEmptyUniqSet, UniqSet )
67 import UniqSupply       ( splitUniqSupply, uniqFromSupply )
68 import PrelNames        ( unpackCStringName, unpackCStringUtf8Name, 
69                           plusIntegerName, timesIntegerName, 
70                           lengthPName, indexPName )
71 import Outputable
72 import UnicodeUtil      ( intsToUtf8, stringToUtf8 )
73 import Util             ( isSingleton, notNull, zipEqual )
74 import ListSetOps       ( assocDefault )
75 import FastString
76 \end{code}
77
78
79
80 %************************************************************************
81 %*                                                                      *
82                 Rebindable syntax
83 %*                                                                      *
84 %************************************************************************
85
86 \begin{code}
87 dsReboundNames :: ReboundNames Id 
88                -> DsM ([CoreBind],      -- Auxiliary bindings
89                        [(Name,Id)])     -- Maps the standard name to its value
90
91 dsReboundNames rebound_ids
92   = mapAndUnzipDs mk_bind rebound_ids   `thenDs` \ (binds_s, prs) ->
93     return (concat binds_s, prs)
94   where
95         -- The cheapo special case can happen when we 
96         -- make an intermediate HsDo when desugaring a RecStmt
97     mk_bind (std_name, HsVar id) = return ([], (std_name, id))
98     mk_bind (std_name, expr)     = dsExpr expr                          `thenDs` \ rhs ->
99                                    newSysLocalDs (exprType rhs)         `thenDs` \ id ->
100                                    return ([NonRec id rhs], (std_name, id))
101
102 lookupReboundName :: [(Name,Id)] -> Name -> CoreExpr
103 lookupReboundName prs std_name
104   = Var (assocDefault (mk_panic std_name) prs std_name)
105   where
106     mk_panic std_name = pprPanic "dsReboundNames" (ptext SLIT("Not found:") <+> ppr std_name)
107 \end{code}
108
109
110 %************************************************************************
111 %*                                                                      *
112 \subsection{Tidying lit pats}
113 %*                                                                      *
114 %************************************************************************
115
116 \begin{code}
117 tidyLitPat :: HsLit -> TypecheckedPat -> TypecheckedPat
118 tidyLitPat (HsChar c) pat = mkCharLitPat c
119 tidyLitPat lit        pat = pat
120
121 tidyNPat :: HsLit -> Type -> TypecheckedPat -> TypecheckedPat
122 tidyNPat (HsString s) _ pat
123   | lengthFS s <= 1     -- Short string literals only
124   = foldr (\c pat -> mkPrefixConPat consDataCon [mkCharLitPat c,pat] stringTy)
125           (mkNilPat stringTy) (unpackIntFS s)
126         -- The stringTy is the type of the whole pattern, not 
127         -- the type to instantiate (:) or [] with!
128   where
129
130 tidyNPat lit lit_ty default_pat
131   | isIntTy lit_ty      = mkPrefixConPat intDataCon    [LitPat (mk_int lit)]    lit_ty 
132   | isFloatTy lit_ty    = mkPrefixConPat floatDataCon  [LitPat (mk_float lit)]  lit_ty 
133   | isDoubleTy lit_ty   = mkPrefixConPat doubleDataCon [LitPat (mk_double lit)] lit_ty 
134   | otherwise           = default_pat
135
136   where
137     mk_int    (HsInteger i) = HsIntPrim i
138
139     mk_float  (HsInteger i) = HsFloatPrim (fromInteger i)
140     mk_float  (HsRat f _)   = HsFloatPrim f
141
142     mk_double (HsInteger i) = HsDoublePrim (fromInteger i)
143     mk_double (HsRat f _)   = HsDoublePrim f
144 \end{code}
145
146
147 %************************************************************************
148 %*                                                                      *
149 \subsection{Building lets}
150 %*                                                                      *
151 %************************************************************************
152
153 Use case, not let for unlifted types.  The simplifier will turn some
154 back again.
155
156 \begin{code}
157 mkDsLet :: CoreBind -> CoreExpr -> CoreExpr
158 mkDsLet (NonRec bndr rhs) body
159   | isUnLiftedType (idType bndr) = Case rhs bndr [(DEFAULT,[],body)]
160 mkDsLet bind body
161   = Let bind body
162
163 mkDsLets :: [CoreBind] -> CoreExpr -> CoreExpr
164 mkDsLets binds body = foldr mkDsLet body binds
165 \end{code}
166
167
168 %************************************************************************
169 %*                                                                      *
170 \subsection{ Selecting match variables}
171 %*                                                                      *
172 %************************************************************************
173
174 We're about to match against some patterns.  We want to make some
175 @Ids@ to use as match variables.  If a pattern has an @Id@ readily at
176 hand, which should indeed be bound to the pattern as a whole, then use it;
177 otherwise, make one up.
178
179 \begin{code}
180 selectMatchVar :: TypecheckedPat -> DsM Id
181 selectMatchVar (VarPat var)     = returnDs var
182 selectMatchVar (AsPat var pat)  = returnDs var
183 selectMatchVar (LazyPat pat)    = selectMatchVar pat
184 selectMatchVar other_pat        = newSysLocalDs (hsPatType other_pat) -- OK, better make up one...
185 \end{code}
186
187
188 %************************************************************************
189 %*                                                                      *
190 %* type synonym EquationInfo and access functions for its pieces        *
191 %*                                                                      *
192 %************************************************************************
193 \subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
194
195 The ``equation info'' used by @match@ is relatively complicated and
196 worthy of a type synonym and a few handy functions.
197
198 \begin{code}
199
200 type EqnNo   = Int
201 type EqnSet  = UniqSet EqnNo
202
203 data EquationInfo
204   = EqnInfo
205         EqnNo           -- The number of the equation
206
207         DsMatchContext  -- The context info is used when producing warnings
208                         -- about shadowed patterns.  It's the context
209                         -- of the *first* thing matched in this group.
210                         -- Should perhaps be a list of them all!
211
212         [TypecheckedPat]    -- The patterns for an eqn
213
214         MatchResult         -- Encapsulates the guards and bindings
215 \end{code}
216
217 \begin{code}
218 data MatchResult
219   = MatchResult
220         CanItFail       -- Tells whether the failure expression is used
221         (CoreExpr -> DsM CoreExpr)
222                         -- Takes a expression to plug in at the
223                         -- failure point(s). The expression should
224                         -- be duplicatable!
225
226 data CanItFail = CanFail | CantFail
227
228 orFail CantFail CantFail = CantFail
229 orFail _        _        = CanFail
230 \end{code}
231
232 Functions on MatchResults
233
234 \begin{code}
235 cantFailMatchResult :: CoreExpr -> MatchResult
236 cantFailMatchResult expr = MatchResult CantFail (\ ignore -> returnDs expr)
237
238 extractMatchResult :: MatchResult -> CoreExpr -> DsM CoreExpr
239 extractMatchResult (MatchResult CantFail match_fn) fail_expr
240   = match_fn (error "It can't fail!")
241
242 extractMatchResult (MatchResult CanFail match_fn) fail_expr
243   = mkFailurePair fail_expr             `thenDs` \ (fail_bind, if_it_fails) ->
244     match_fn if_it_fails                `thenDs` \ body ->
245     returnDs (mkDsLet fail_bind body)
246
247
248 combineMatchResults :: MatchResult -> MatchResult -> MatchResult
249 combineMatchResults (MatchResult CanFail      body_fn1)
250                     (MatchResult can_it_fail2 body_fn2)
251   = MatchResult can_it_fail2 body_fn
252   where
253     body_fn fail = body_fn2 fail                        `thenDs` \ body2 ->
254                    mkFailurePair body2                  `thenDs` \ (fail_bind, duplicatable_expr) ->
255                    body_fn1 duplicatable_expr           `thenDs` \ body1 ->
256                    returnDs (Let fail_bind body1)
257
258 combineMatchResults match_result1@(MatchResult CantFail body_fn1) match_result2
259   = match_result1
260
261
262 adjustMatchResult :: (CoreExpr -> CoreExpr) -> MatchResult -> MatchResult
263 adjustMatchResult encl_fn (MatchResult can_it_fail body_fn)
264   = MatchResult can_it_fail (\fail -> body_fn fail      `thenDs` \ body ->
265                                       returnDs (encl_fn body))
266
267 adjustMatchResultDs :: (CoreExpr -> DsM CoreExpr) -> MatchResult -> MatchResult
268 adjustMatchResultDs encl_fn (MatchResult can_it_fail body_fn)
269   = MatchResult can_it_fail (\fail -> body_fn fail      `thenDs` \ body ->
270                                       encl_fn body)
271
272
273 mkCoLetsMatchResult :: [CoreBind] -> MatchResult -> MatchResult
274 mkCoLetsMatchResult binds match_result
275   = adjustMatchResult (mkDsLets binds) match_result
276
277
278 mkGuardedMatchResult :: CoreExpr -> MatchResult -> MatchResult
279 mkGuardedMatchResult pred_expr (MatchResult can_it_fail body_fn)
280   = MatchResult CanFail (\fail -> body_fn fail  `thenDs` \ body ->
281                                   returnDs (mkIfThenElse pred_expr body fail))
282
283 mkCoPrimCaseMatchResult :: Id                           -- Scrutinee
284                     -> [(Literal, MatchResult)]         -- Alternatives
285                     -> MatchResult
286 mkCoPrimCaseMatchResult var match_alts
287   = MatchResult CanFail mk_case
288   where
289     mk_case fail
290       = mapDs (mk_alt fail) match_alts          `thenDs` \ alts ->
291         returnDs (Case (Var var) var ((DEFAULT, [], fail) : alts))
292
293     mk_alt fail (lit, MatchResult _ body_fn) = body_fn fail     `thenDs` \ body ->
294                                                returnDs (LitAlt lit, [], body)
295
296
297 mkCoAlgCaseMatchResult :: Id                                    -- Scrutinee
298                     -> [(DataCon, [CoreBndr], MatchResult)]     -- Alternatives
299                     -> MatchResult
300
301 mkCoAlgCaseMatchResult var match_alts
302   | isNewTyCon tycon            -- Newtype case; use a let
303   = ASSERT( null (tail match_alts) && null (tail arg_ids) )
304     mkCoLetsMatchResult [NonRec arg_id newtype_rhs] match_result
305
306   | isPArrFakeAlts match_alts   -- Sugared parallel array; use a literal case 
307   = MatchResult CanFail mk_parrCase
308
309   | otherwise                   -- Datatype case; use a case
310   = MatchResult fail_flag mk_case
311   where
312         -- Common stuff
313     scrut_ty = idType var
314     tycon    = tcTyConAppTyCon scrut_ty         -- Newtypes must be opaque here
315
316         -- Stuff for newtype
317     (_, arg_ids, match_result) = head match_alts
318     arg_id                     = head arg_ids
319     newtype_rhs                = mkNewTypeBody tycon (idType arg_id) (Var var)
320                 
321         -- Stuff for data types
322     data_cons      = tyConDataCons tycon
323     match_results  = [match_result | (_,_,match_result) <- match_alts]
324
325     fail_flag | exhaustive_case
326               = foldr1 orFail [can_it_fail | MatchResult can_it_fail _ <- match_results]
327               | otherwise
328               = CanFail
329
330     wild_var = mkWildId (idType var)
331     mk_case fail = mapDs (mk_alt fail) match_alts       `thenDs` \ alts ->
332                    returnDs (Case (Var var) wild_var (mk_default fail ++ alts))
333
334     mk_alt fail (con, args, MatchResult _ body_fn)
335         = body_fn fail                          `thenDs` \ body ->
336           getUniquesDs                          `thenDs` \ us ->
337           returnDs (mkReboxingAlt us con args body)
338
339     mk_default fail | exhaustive_case = []
340                     | otherwise       = [(DEFAULT, [], fail)]
341
342     un_mentioned_constructors
343         = mkUniqSet data_cons `minusUniqSet` mkUniqSet [ con | (con, _, _) <- match_alts]
344     exhaustive_case = isEmptyUniqSet un_mentioned_constructors
345
346         -- Stuff for parallel arrays
347         -- 
348         -- * the following is to desugar cases over fake constructors for
349         --   parallel arrays, which are introduced by `tidy1' in the `PArrPat'
350         --   case
351         --
352         -- Concerning `isPArrFakeAlts':
353         --
354         -- * it is *not* sufficient to just check the type of the type
355         --   constructor, as we have to be careful not to confuse the real
356         --   representation of parallel arrays with the fake constructors;
357         --   moreover, a list of alternatives must not mix fake and real
358         --   constructors (this is checked earlier on)
359         --
360         -- FIXME: We actually go through the whole list and make sure that
361         --        either all or none of the constructors are fake parallel
362         --        array constructors.  This is to spot equations that mix fake
363         --        constructors with the real representation defined in
364         --        `PrelPArr'.  It would be nicer to spot this situation
365         --        earlier and raise a proper error message, but it can really
366         --        only happen in `PrelPArr' anyway.
367         --
368     isPArrFakeAlts [(dcon, _, _)]      = isPArrFakeCon dcon
369     isPArrFakeAlts ((dcon, _, _):alts) = 
370       case (isPArrFakeCon dcon, isPArrFakeAlts alts) of
371         (True , True ) -> True
372         (False, False) -> False
373         _              -> 
374           panic "DsUtils: You may not mix `[:...:]' with `PArr' patterns"
375     --
376     mk_parrCase fail =             
377       dsLookupGlobalId lengthPName                      `thenDs` \lengthP  ->
378       unboxAlt                                          `thenDs` \alt      ->
379       returnDs (Case (len lengthP) (mkWildId intTy) [alt])
380       where
381         elemTy      = case splitTyConApp (idType var) of
382                         (_, [elemTy]) -> elemTy
383                         _               -> panic panicMsg
384         panicMsg    = "DsUtils.mkCoAlgCaseMatchResult: not a parallel array?"
385         len lengthP = mkApps (Var lengthP) [Type elemTy, Var var]
386         --
387         unboxAlt = 
388           newSysLocalDs intPrimTy                       `thenDs` \l        ->
389           dsLookupGlobalId indexPName           `thenDs` \indexP   ->
390           mapDs (mkAlt indexP) match_alts               `thenDs` \alts     ->
391           returnDs (DataAlt intDataCon, [l], (Case (Var l) wild (dft : alts)))
392           where
393             wild = mkWildId intPrimTy
394             dft  = (DEFAULT, [], fail)
395         --
396         -- each alternative matches one array length (corresponding to one
397         -- fake array constructor), so the match is on a literal; each
398         -- alternative's body is extended by a local binding for each
399         -- constructor argument, which are bound to array elements starting
400         -- with the first
401         --
402         mkAlt indexP (con, args, MatchResult _ bodyFun) = 
403           bodyFun fail                                  `thenDs` \body     ->
404           returnDs (LitAlt lit, [], mkDsLets binds body)
405           where
406             lit   = MachInt $ toInteger (dataConSourceArity con)
407             binds = [NonRec arg (indexExpr i) | (i, arg) <- zip [1..] args]
408             --
409             indexExpr i = mkApps (Var indexP) [Type elemTy, Var var, mkIntExpr i]
410 \end{code}
411
412
413 %************************************************************************
414 %*                                                                      *
415 \subsection{Desugarer's versions of some Core functions}
416 %*                                                                      *
417 %************************************************************************
418
419 \begin{code}
420 mkErrorAppDs :: Id              -- The error function
421              -> Type            -- Type to which it should be applied
422              -> String          -- The error message string to pass
423              -> DsM CoreExpr
424
425 mkErrorAppDs err_id ty msg
426   = getSrcLocDs                 `thenDs` \ src_loc ->
427     let
428         full_msg = showSDoc (hcat [ppr src_loc, text "|", text msg])
429         core_msg = Lit (MachStr (mkFastString (stringToUtf8 full_msg)))
430     in
431     returnDs (mkApps (Var err_id) [Type ty, core_msg])
432 \end{code}
433
434
435 *************************************************************
436 %*                                                                      *
437 \subsection{Making literals}
438 %*                                                                      *
439 %************************************************************************
440
441 \begin{code}
442 mkCharExpr    :: Int        -> CoreExpr      -- Returns C# c :: Int
443 mkIntExpr     :: Integer    -> CoreExpr      -- Returns I# i :: Int
444 mkIntegerExpr :: Integer    -> DsM CoreExpr  -- Result :: Integer
445 mkStringLit   :: String     -> DsM CoreExpr  -- Result :: String
446 mkStringLitFS :: FastString -> DsM CoreExpr  -- Result :: String
447
448 mkIntExpr  i = mkConApp intDataCon  [mkIntLit i]
449 mkCharExpr c = mkConApp charDataCon [mkLit (MachChar c)]
450
451 mkIntegerExpr i
452   | inIntRange i        -- Small enough, so start from an Int
453   = returnDs (mkSmallIntegerLit i)
454
455 -- Special case for integral literals with a large magnitude:
456 -- They are transformed into an expression involving only smaller
457 -- integral literals. This improves constant folding.
458
459   | otherwise           -- Big, so start from a string
460   = dsLookupGlobalId plusIntegerName            `thenDs` \ plus_id ->
461     dsLookupGlobalId timesIntegerName   `thenDs` \ times_id ->
462     let 
463         plus a b  = Var plus_id  `App` a `App` b
464         times a b = Var times_id `App` a `App` b
465
466         -- Transform i into (x1 + (x2 + (x3 + (...) * b) * b) * b) with abs xi <= b
467         horner :: Integer -> Integer -> CoreExpr
468         horner b i | abs q <= 1 = if r == 0 || r == i 
469                                   then mkSmallIntegerLit i 
470                                   else mkSmallIntegerLit r `plus` mkSmallIntegerLit (i-r)
471                    | r == 0     =                             horner b q `times` mkSmallIntegerLit b
472                    | otherwise  = mkSmallIntegerLit r `plus` (horner b q `times` mkSmallIntegerLit b)
473                    where
474                      (q,r) = i `quotRem` b
475
476     in
477     returnDs (horner tARGET_MAX_INT i)
478
479 mkSmallIntegerLit i = mkConApp smallIntegerDataCon [mkIntLit i]
480
481 mkStringLit str = mkStringLitFS (mkFastString str)
482
483 mkStringLitFS str
484   | nullFastString str
485   = returnDs (mkNilExpr charTy)
486
487   | lengthFS str == 1
488   = let
489         the_char = mkCharExpr (headIntFS str)
490     in
491     returnDs (mkConsExpr charTy the_char (mkNilExpr charTy))
492
493   | all safeChar int_chars
494   = dsLookupGlobalId unpackCStringName  `thenDs` \ unpack_id ->
495     returnDs (App (Var unpack_id) (Lit (MachStr str)))
496
497   | otherwise
498   = dsLookupGlobalId unpackCStringUtf8Name      `thenDs` \ unpack_id ->
499     returnDs (App (Var unpack_id) (Lit (MachStr (mkFastString (intsToUtf8 int_chars)))))
500
501   where
502     int_chars = unpackIntFS str
503     safeChar c = c >= 1 && c <= 0xFF
504 \end{code}
505
506
507 %************************************************************************
508 %*                                                                      *
509 \subsection[mkSelectorBind]{Make a selector bind}
510 %*                                                                      *
511 %************************************************************************
512
513 This is used in various places to do with lazy patterns.
514 For each binder $b$ in the pattern, we create a binding:
515 \begin{verbatim}
516     b = case v of pat' -> b'
517 \end{verbatim}
518 where @pat'@ is @pat@ with each binder @b@ cloned into @b'@.
519
520 ToDo: making these bindings should really depend on whether there's
521 much work to be done per binding.  If the pattern is complex, it
522 should be de-mangled once, into a tuple (and then selected from).
523 Otherwise the demangling can be in-line in the bindings (as here).
524
525 Boring!  Boring!  One error message per binder.  The above ToDo is
526 even more helpful.  Something very similar happens for pattern-bound
527 expressions.
528
529 \begin{code}
530 mkSelectorBinds :: TypecheckedPat       -- The pattern
531                 -> CoreExpr             -- Expression to which the pattern is bound
532                 -> DsM [(Id,CoreExpr)]
533
534 mkSelectorBinds (VarPat v) val_expr
535   = returnDs [(v, val_expr)]
536
537 mkSelectorBinds pat val_expr
538   | isSingleton binders || is_simple_pat pat
539   =     -- Given   p = e, where p binds x,y
540         -- we are going to make
541         --      v = p   (where v is fresh)
542         --      x = case v of p -> x
543         --      y = case v of p -> x
544
545         -- Make up 'v'
546         -- NB: give it the type of *pattern* p, not the type of the *rhs* e.
547         -- This does not matter after desugaring, but there's a subtle 
548         -- issue with implicit parameters. Consider
549         --      (x,y) = ?i
550         -- Then, ?i is given type {?i :: Int}, a SourceType, which is opaque
551         -- to the desugarer.  (Why opaque?  Because newtypes have to be.  Why
552         -- does it get that type?  So that when we abstract over it we get the
553         -- right top-level type  (?i::Int) => ...)
554         --
555         -- So to get the type of 'v', use the pattern not the rhs.  Often more
556         -- efficient too.
557     newSysLocalDs (hsPatType pat)       `thenDs` \ val_var ->
558
559         -- For the error message we make one error-app, to avoid duplication.
560         -- But we need it at different types... so we use coerce for that
561     mkErrorAppDs iRREFUT_PAT_ERROR_ID 
562                  unitTy (showSDoc (ppr pat))    `thenDs` \ err_expr ->
563     newSysLocalDs unitTy                        `thenDs` \ err_var ->
564     mapDs (mk_bind val_var err_var) binders     `thenDs` \ binds ->
565     returnDs ( (val_var, val_expr) : 
566                (err_var, err_expr) :
567                binds )
568
569
570   | otherwise
571   = mkErrorAppDs iRREFUT_PAT_ERROR_ID 
572                  tuple_ty (showSDoc (ppr pat))                  `thenDs` \ error_expr ->
573     matchSimply val_expr PatBindRhs pat local_tuple error_expr  `thenDs` \ tuple_expr ->
574     newSysLocalDs tuple_ty                                      `thenDs` \ tuple_var ->
575     let
576         mk_tup_bind binder
577           = (binder, mkTupleSelector binders binder tuple_var (Var tuple_var))
578     in
579     returnDs ( (tuple_var, tuple_expr) : map mk_tup_bind binders )
580   where
581     binders     = collectPatBinders pat
582     local_tuple = mkTupleExpr binders
583     tuple_ty    = exprType local_tuple
584
585     mk_bind scrut_var err_var bndr_var
586     -- (mk_bind sv err_var) generates
587     --          bv = case sv of { pat -> bv; other -> coerce (type-of-bv) err_var }
588     -- Remember, pat binds bv
589       = matchSimply (Var scrut_var) PatBindRhs pat
590                     (Var bndr_var) error_expr                   `thenDs` \ rhs_expr ->
591         returnDs (bndr_var, rhs_expr)
592       where
593         error_expr = mkCoerce (idType bndr_var) (Var err_var)
594
595     is_simple_pat (TuplePat ps Boxed)    = all is_triv_pat ps
596     is_simple_pat (ConPatOut _ ps _ _ _) = all is_triv_pat (hsConArgs ps)
597     is_simple_pat (VarPat _)             = True
598     is_simple_pat (ParPat p)             = is_simple_pat p
599     is_simple_pat other                  = False
600
601     is_triv_pat (VarPat v)  = True
602     is_triv_pat (WildPat _) = True
603     is_triv_pat (ParPat p)  = is_triv_pat p
604     is_triv_pat other       = False
605 \end{code}
606
607
608 %************************************************************************
609 %*                                                                      *
610                 Tuples
611 %*                                                                      *
612 %************************************************************************
613
614 @mkTupleExpr@ builds a tuple; the inverse to @mkTupleSelector@.  
615
616 * If it has only one element, it is the identity function.
617
618 * If there are more elements than a big tuple can have, it nests 
619   the tuples.  
620
621 Nesting policy.  Better a 2-tuple of 10-tuples (3 objects) than
622 a 10-tuple of 2-tuples (11 objects).  So we want the leaves to be big.
623
624 \begin{code}
625 mkTupleExpr :: [Id] -> CoreExpr
626 mkTupleExpr ids = mkBigCoreTup (map Var ids)
627
628 -- corresponding type
629 mkTupleType :: [Id] -> Type
630 mkTupleType ids = mkBigTuple mkCoreTupTy (map idType ids)
631
632 mkBigCoreTup :: [CoreExpr] -> CoreExpr
633 mkBigCoreTup = mkBigTuple mkCoreTup
634
635 mkBigTuple :: ([a] -> a) -> [a] -> a
636 mkBigTuple small_tuple as = mk_big_tuple (chunkify as)
637   where
638         -- Each sub-list is short enough to fit in a tuple
639     mk_big_tuple [as] = small_tuple as
640     mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s))
641
642 chunkify :: [a] -> [[a]]
643 -- The sub-lists of the result all have length <= mAX_TUPLE_SIZE
644 -- But there may be more than mAX_TUPLE_SIZE sub-lists
645 chunkify xs
646   | n_xs <= mAX_TUPLE_SIZE = {- pprTrace "Small" (ppr n_xs) -} [xs] 
647   | otherwise              = {- pprTrace "Big"   (ppr n_xs) -} (split xs)
648   where
649     n_xs     = length xs
650     split [] = []
651     split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
652 \end{code}
653
654
655 @mkTupleSelector@ builds a selector which scrutises the given
656 expression and extracts the one name from the list given.
657 If you want the no-shadowing rule to apply, the caller
658 is responsible for making sure that none of these names
659 are in scope.
660
661 If there is just one id in the ``tuple'', then the selector is
662 just the identity.
663
664 If it's big, it does nesting
665         mkTupleSelector [a,b,c,d] b v e
666           = case e of v { 
667                 (p,q) -> case p of p {
668                            (a,b) -> b }}
669 We use 'tpl' vars for the p,q, since shadowing does not matter.
670
671 In fact, it's more convenient to generate it innermost first, getting
672
673         case (case e of v 
674                 (p,q) -> p) of p
675           (a,b) -> b
676
677 \begin{code}
678 mkTupleSelector :: [Id]         -- The tuple args
679                 -> Id           -- The selected one
680                 -> Id           -- A variable of the same type as the scrutinee
681                 -> CoreExpr     -- Scrutinee
682                 -> CoreExpr
683
684 mkTupleSelector vars the_var scrut_var scrut
685   = mk_tup_sel (chunkify vars) the_var
686   where
687     mk_tup_sel [vars] the_var = mkCoreSel vars the_var scrut_var scrut
688     mk_tup_sel vars_s the_var = mkCoreSel group the_var tpl_v $
689                                 mk_tup_sel (chunkify tpl_vs) tpl_v
690         where
691           tpl_tys = [mkCoreTupTy (map idType gp) | gp <- vars_s]
692           tpl_vs  = mkTemplateLocals tpl_tys
693           [(tpl_v, group)] = [(tpl,gp) | (tpl,gp) <- zipEqual "mkTupleSelector" tpl_vs vars_s,
694                                          the_var `elem` gp ]
695 \end{code}
696
697 A generalization of @mkTupleSelector@, allowing the body
698 of the case to be an arbitrary expression.
699
700 If the tuple is big, it is nested:
701
702         mkTupleCase uniqs [a,b,c,d] body v e
703           = case e of v { (p,q) ->
704             case p of p { (a,b) ->
705             case q of q { (c,d) ->
706             body }}}
707
708 To avoid shadowing, we use uniqs to invent new variables p,q.
709
710 ToDo: eliminate cases where none of the variables are needed.
711
712 \begin{code}
713 mkTupleCase
714         :: UniqSupply   -- for inventing names of intermediate variables
715         -> [Id]         -- the tuple args
716         -> CoreExpr     -- body of the case
717         -> Id           -- a variable of the same type as the scrutinee
718         -> CoreExpr     -- scrutinee
719         -> CoreExpr
720
721 mkTupleCase uniqs vars body scrut_var scrut
722   = mk_tuple_case uniqs (chunkify vars) body
723   where
724     mk_tuple_case us [vars] body
725       = mkSmallTupleCase vars body scrut_var scrut
726     mk_tuple_case us vars_s body
727       = let
728             (us', vars', body') = foldr one_tuple_case (us, [], body) vars_s
729         in
730         mk_tuple_case us' (chunkify vars') body'
731     one_tuple_case chunk_vars (us, vs, body)
732       = let
733             (us1, us2) = splitUniqSupply us
734             scrut_var = mkSysLocal FSLIT("ds") (uniqFromSupply us1)
735                         (mkCoreTupTy (map idType chunk_vars))
736             body' = mkSmallTupleCase chunk_vars body scrut_var (Var scrut_var)
737         in (us2, scrut_var:vs, body')
738 \end{code}
739
740 The same, but with a tuple small enough not to need nesting.
741
742 \begin{code}
743 mkSmallTupleCase
744         :: [Id]         -- the tuple args
745         -> CoreExpr     -- body of the case
746         -> Id           -- a variable of the same type as the scrutinee
747         -> CoreExpr     -- scrutinee
748         -> CoreExpr
749
750 mkSmallTupleCase [var] body _scrut_var scrut
751   = bindNonRec var scrut body
752 mkSmallTupleCase vars body scrut_var scrut
753   = Case scrut scrut_var [(DataAlt (tupleCon Boxed (length vars)), vars, body)]
754 \end{code}
755
756 %************************************************************************
757 %*                                                                      *
758 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
759 %*                                                                      *
760 %************************************************************************
761
762 Call the constructor Ids when building explicit lists, so that they
763 interact well with rules.
764
765 \begin{code}
766 mkNilExpr :: Type -> CoreExpr
767 mkNilExpr ty = mkConApp nilDataCon [Type ty]
768
769 mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
770 mkConsExpr ty hd tl = mkConApp consDataCon [Type ty, hd, tl]
771
772 mkListExpr :: Type -> [CoreExpr] -> CoreExpr
773 mkListExpr ty xs = foldr (mkConsExpr ty) (mkNilExpr ty) xs
774                             
775
776 -- The next three functions make tuple types, constructors and selectors,
777 -- with the rule that a 1-tuple is represented by the thing itselg
778 mkCoreTupTy :: [Type] -> Type
779 mkCoreTupTy [ty] = ty
780 mkCoreTupTy tys  = mkTupleTy Boxed (length tys) tys
781
782 mkCoreTup :: [CoreExpr] -> CoreExpr                         
783 -- Builds exactly the specified tuple.
784 -- No fancy business for big tuples
785 mkCoreTup []  = Var unitDataConId
786 mkCoreTup [c] = c
787 mkCoreTup cs  = mkConApp (tupleCon Boxed (length cs))
788                          (map (Type . exprType) cs ++ cs)
789
790 mkCoreSel :: [Id]       -- The tuple args
791           -> Id         -- The selected one
792           -> Id         -- A variable of the same type as the scrutinee
793           -> CoreExpr   -- Scrutinee
794           -> CoreExpr
795 -- mkCoreSel [x,y,z] x v e
796 -- ===>  case e of v { (x,y,z) -> x
797 mkCoreSel [var] should_be_the_same_var scrut_var scrut
798   = ASSERT(var == should_be_the_same_var)
799     scrut
800
801 mkCoreSel vars the_var scrut_var scrut
802   = ASSERT( notNull vars )
803     Case scrut scrut_var 
804          [(DataAlt (tupleCon Boxed (length vars)), vars, Var the_var)]
805 \end{code}
806
807
808 %************************************************************************
809 %*                                                                      *
810 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
811 %*                                                                      *
812 %************************************************************************
813
814 Generally, we handle pattern matching failure like this: let-bind a
815 fail-variable, and use that variable if the thing fails:
816 \begin{verbatim}
817         let fail.33 = error "Help"
818         in
819         case x of
820                 p1 -> ...
821                 p2 -> fail.33
822                 p3 -> fail.33
823                 p4 -> ...
824 \end{verbatim}
825 Then
826 \begin{itemize}
827 \item
828 If the case can't fail, then there'll be no mention of @fail.33@, and the
829 simplifier will later discard it.
830
831 \item
832 If it can fail in only one way, then the simplifier will inline it.
833
834 \item
835 Only if it is used more than once will the let-binding remain.
836 \end{itemize}
837
838 There's a problem when the result of the case expression is of
839 unboxed type.  Then the type of @fail.33@ is unboxed too, and
840 there is every chance that someone will change the let into a case:
841 \begin{verbatim}
842         case error "Help" of
843           fail.33 -> case ....
844 \end{verbatim}
845
846 which is of course utterly wrong.  Rather than drop the condition that
847 only boxed types can be let-bound, we just turn the fail into a function
848 for the primitive case:
849 \begin{verbatim}
850         let fail.33 :: Void -> Int#
851             fail.33 = \_ -> error "Help"
852         in
853         case x of
854                 p1 -> ...
855                 p2 -> fail.33 void
856                 p3 -> fail.33 void
857                 p4 -> ...
858 \end{verbatim}
859
860 Now @fail.33@ is a function, so it can be let-bound.
861
862 \begin{code}
863 mkFailurePair :: CoreExpr       -- Result type of the whole case expression
864               -> DsM (CoreBind, -- Binds the newly-created fail variable
865                                 -- to either the expression or \ _ -> expression
866                       CoreExpr) -- Either the fail variable, or fail variable
867                                 -- applied to unit tuple
868 mkFailurePair expr
869   | isUnLiftedType ty
870   = newFailLocalDs (unitTy `mkFunTy` ty)        `thenDs` \ fail_fun_var ->
871     newSysLocalDs unitTy                        `thenDs` \ fail_fun_arg ->
872     returnDs (NonRec fail_fun_var (Lam fail_fun_arg expr),
873               App (Var fail_fun_var) (Var unitDataConId))
874
875   | otherwise
876   = newFailLocalDs ty           `thenDs` \ fail_var ->
877     returnDs (NonRec fail_var expr, Var fail_var)
878   where
879     ty = exprType expr
880 \end{code}
881
882