[project @ 2003-10-09 11:58:39 by simonpj]
[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, 
62                           floatDataCon, 
63                           doubleDataCon,
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 )
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       = mappM (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 = mappM (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           newUniqueSupply                       `thenDs` \ us ->
337           returnDs (mkReboxingAlt (uniqsFromSupply 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           mappM (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   = dsLookupDataCon  smallIntegerDataConName    `thenDs` \ integer_dc ->
454     returnDs (mkSmallIntegerLit integer_dc i)
455
456 -- Special case for integral literals with a large magnitude:
457 -- They are transformed into an expression involving only smaller
458 -- integral literals. This improves constant folding.
459
460   | otherwise           -- Big, so start from a string
461   = dsLookupGlobalId plusIntegerName            `thenDs` \ plus_id ->
462     dsLookupGlobalId timesIntegerName           `thenDs` \ times_id ->
463     dsLookupDataCon  smallIntegerDataConName    `thenDs` \ integer_dc ->
464     let 
465         lit i = mkSmallIntegerLit integer_dc i
466         plus a b  = Var plus_id  `App` a `App` b
467         times a b = Var times_id `App` a `App` b
468
469         -- Transform i into (x1 + (x2 + (x3 + (...) * b) * b) * b) with abs xi <= b
470         horner :: Integer -> Integer -> CoreExpr
471         horner b i | abs q <= 1 = if r == 0 || r == i 
472                                   then lit i 
473                                   else lit r `plus` lit (i-r)
474                    | r == 0     =               horner b q `times` lit b
475                    | otherwise  = lit r `plus` (horner b q `times` lit b)
476                    where
477                      (q,r) = i `quotRem` b
478
479     in
480     returnDs (horner tARGET_MAX_INT i)
481
482 mkSmallIntegerLit small_integer_data_con i = mkConApp small_integer_data_con [mkIntLit i]
483
484 mkStringLit str = mkStringLitFS (mkFastString str)
485
486 mkStringLitFS str
487   | nullFastString str
488   = returnDs (mkNilExpr charTy)
489
490   | lengthFS str == 1
491   = let
492         the_char = mkCharExpr (headIntFS str)
493     in
494     returnDs (mkConsExpr charTy the_char (mkNilExpr charTy))
495
496   | all safeChar int_chars
497   = dsLookupGlobalId unpackCStringName  `thenDs` \ unpack_id ->
498     returnDs (App (Var unpack_id) (Lit (MachStr str)))
499
500   | otherwise
501   = dsLookupGlobalId unpackCStringUtf8Name      `thenDs` \ unpack_id ->
502     returnDs (App (Var unpack_id) (Lit (MachStr (mkFastString (intsToUtf8 int_chars)))))
503
504   where
505     int_chars = unpackIntFS str
506     safeChar c = c >= 1 && c <= 0xFF
507 \end{code}
508
509
510 %************************************************************************
511 %*                                                                      *
512 \subsection[mkSelectorBind]{Make a selector bind}
513 %*                                                                      *
514 %************************************************************************
515
516 This is used in various places to do with lazy patterns.
517 For each binder $b$ in the pattern, we create a binding:
518 \begin{verbatim}
519     b = case v of pat' -> b'
520 \end{verbatim}
521 where @pat'@ is @pat@ with each binder @b@ cloned into @b'@.
522
523 ToDo: making these bindings should really depend on whether there's
524 much work to be done per binding.  If the pattern is complex, it
525 should be de-mangled once, into a tuple (and then selected from).
526 Otherwise the demangling can be in-line in the bindings (as here).
527
528 Boring!  Boring!  One error message per binder.  The above ToDo is
529 even more helpful.  Something very similar happens for pattern-bound
530 expressions.
531
532 \begin{code}
533 mkSelectorBinds :: TypecheckedPat       -- The pattern
534                 -> CoreExpr             -- Expression to which the pattern is bound
535                 -> DsM [(Id,CoreExpr)]
536
537 mkSelectorBinds (VarPat v) val_expr
538   = returnDs [(v, val_expr)]
539
540 mkSelectorBinds pat val_expr
541   | isSingleton binders || is_simple_pat pat
542   =     -- Given   p = e, where p binds x,y
543         -- we are going to make
544         --      v = p   (where v is fresh)
545         --      x = case v of p -> x
546         --      y = case v of p -> x
547
548         -- Make up 'v'
549         -- NB: give it the type of *pattern* p, not the type of the *rhs* e.
550         -- This does not matter after desugaring, but there's a subtle 
551         -- issue with implicit parameters. Consider
552         --      (x,y) = ?i
553         -- Then, ?i is given type {?i :: Int}, a PredType, which is opaque
554         -- to the desugarer.  (Why opaque?  Because newtypes have to be.  Why
555         -- does it get that type?  So that when we abstract over it we get the
556         -- right top-level type  (?i::Int) => ...)
557         --
558         -- So to get the type of 'v', use the pattern not the rhs.  Often more
559         -- efficient too.
560     newSysLocalDs (hsPatType pat)       `thenDs` \ val_var ->
561
562         -- For the error message we make one error-app, to avoid duplication.
563         -- But we need it at different types... so we use coerce for that
564     mkErrorAppDs iRREFUT_PAT_ERROR_ID 
565                  unitTy (showSDoc (ppr pat))    `thenDs` \ err_expr ->
566     newSysLocalDs unitTy                        `thenDs` \ err_var ->
567     mappM (mk_bind val_var err_var) binders     `thenDs` \ binds ->
568     returnDs ( (val_var, val_expr) : 
569                (err_var, err_expr) :
570                binds )
571
572
573   | otherwise
574   = mkErrorAppDs iRREFUT_PAT_ERROR_ID 
575                  tuple_ty (showSDoc (ppr pat))                  `thenDs` \ error_expr ->
576     matchSimply val_expr PatBindRhs pat local_tuple error_expr  `thenDs` \ tuple_expr ->
577     newSysLocalDs tuple_ty                                      `thenDs` \ tuple_var ->
578     let
579         mk_tup_bind binder
580           = (binder, mkTupleSelector binders binder tuple_var (Var tuple_var))
581     in
582     returnDs ( (tuple_var, tuple_expr) : map mk_tup_bind binders )
583   where
584     binders     = collectPatBinders pat
585     local_tuple = mkTupleExpr binders
586     tuple_ty    = exprType local_tuple
587
588     mk_bind scrut_var err_var bndr_var
589     -- (mk_bind sv err_var) generates
590     --          bv = case sv of { pat -> bv; other -> coerce (type-of-bv) err_var }
591     -- Remember, pat binds bv
592       = matchSimply (Var scrut_var) PatBindRhs pat
593                     (Var bndr_var) error_expr                   `thenDs` \ rhs_expr ->
594         returnDs (bndr_var, rhs_expr)
595       where
596         error_expr = mkCoerce (idType bndr_var) (Var err_var)
597
598     is_simple_pat (TuplePat ps Boxed)    = all is_triv_pat ps
599     is_simple_pat (ConPatOut _ ps _ _ _) = all is_triv_pat (hsConArgs ps)
600     is_simple_pat (VarPat _)             = True
601     is_simple_pat (ParPat p)             = is_simple_pat p
602     is_simple_pat other                  = False
603
604     is_triv_pat (VarPat v)  = True
605     is_triv_pat (WildPat _) = True
606     is_triv_pat (ParPat p)  = is_triv_pat p
607     is_triv_pat other       = False
608 \end{code}
609
610
611 %************************************************************************
612 %*                                                                      *
613                 Tuples
614 %*                                                                      *
615 %************************************************************************
616
617 @mkTupleExpr@ builds a tuple; the inverse to @mkTupleSelector@.  
618
619 * If it has only one element, it is the identity function.
620
621 * If there are more elements than a big tuple can have, it nests 
622   the tuples.  
623
624 Nesting policy.  Better a 2-tuple of 10-tuples (3 objects) than
625 a 10-tuple of 2-tuples (11 objects).  So we want the leaves to be big.
626
627 \begin{code}
628 mkTupleExpr :: [Id] -> CoreExpr
629 mkTupleExpr ids = mkBigCoreTup (map Var ids)
630
631 -- corresponding type
632 mkTupleType :: [Id] -> Type
633 mkTupleType ids = mkBigTuple mkCoreTupTy (map idType ids)
634
635 mkBigCoreTup :: [CoreExpr] -> CoreExpr
636 mkBigCoreTup = mkBigTuple mkCoreTup
637
638 mkBigTuple :: ([a] -> a) -> [a] -> a
639 mkBigTuple small_tuple as = mk_big_tuple (chunkify as)
640   where
641         -- Each sub-list is short enough to fit in a tuple
642     mk_big_tuple [as] = small_tuple as
643     mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s))
644
645 chunkify :: [a] -> [[a]]
646 -- The sub-lists of the result all have length <= mAX_TUPLE_SIZE
647 -- But there may be more than mAX_TUPLE_SIZE sub-lists
648 chunkify xs
649   | n_xs <= mAX_TUPLE_SIZE = {- pprTrace "Small" (ppr n_xs) -} [xs] 
650   | otherwise              = {- pprTrace "Big"   (ppr n_xs) -} (split xs)
651   where
652     n_xs     = length xs
653     split [] = []
654     split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
655 \end{code}
656
657
658 @mkTupleSelector@ builds a selector which scrutises the given
659 expression and extracts the one name from the list given.
660 If you want the no-shadowing rule to apply, the caller
661 is responsible for making sure that none of these names
662 are in scope.
663
664 If there is just one id in the ``tuple'', then the selector is
665 just the identity.
666
667 If it's big, it does nesting
668         mkTupleSelector [a,b,c,d] b v e
669           = case e of v { 
670                 (p,q) -> case p of p {
671                            (a,b) -> b }}
672 We use 'tpl' vars for the p,q, since shadowing does not matter.
673
674 In fact, it's more convenient to generate it innermost first, getting
675
676         case (case e of v 
677                 (p,q) -> p) of p
678           (a,b) -> b
679
680 \begin{code}
681 mkTupleSelector :: [Id]         -- The tuple args
682                 -> Id           -- The selected one
683                 -> Id           -- A variable of the same type as the scrutinee
684                 -> CoreExpr     -- Scrutinee
685                 -> CoreExpr
686
687 mkTupleSelector vars the_var scrut_var scrut
688   = mk_tup_sel (chunkify vars) the_var
689   where
690     mk_tup_sel [vars] the_var = mkCoreSel vars the_var scrut_var scrut
691     mk_tup_sel vars_s the_var = mkCoreSel group the_var tpl_v $
692                                 mk_tup_sel (chunkify tpl_vs) tpl_v
693         where
694           tpl_tys = [mkCoreTupTy (map idType gp) | gp <- vars_s]
695           tpl_vs  = mkTemplateLocals tpl_tys
696           [(tpl_v, group)] = [(tpl,gp) | (tpl,gp) <- zipEqual "mkTupleSelector" tpl_vs vars_s,
697                                          the_var `elem` gp ]
698 \end{code}
699
700 A generalization of @mkTupleSelector@, allowing the body
701 of the case to be an arbitrary expression.
702
703 If the tuple is big, it is nested:
704
705         mkTupleCase uniqs [a,b,c,d] body v e
706           = case e of v { (p,q) ->
707             case p of p { (a,b) ->
708             case q of q { (c,d) ->
709             body }}}
710
711 To avoid shadowing, we use uniqs to invent new variables p,q.
712
713 ToDo: eliminate cases where none of the variables are needed.
714
715 \begin{code}
716 mkTupleCase
717         :: UniqSupply   -- for inventing names of intermediate variables
718         -> [Id]         -- the tuple args
719         -> CoreExpr     -- body of the case
720         -> Id           -- a variable of the same type as the scrutinee
721         -> CoreExpr     -- scrutinee
722         -> CoreExpr
723
724 mkTupleCase uniqs vars body scrut_var scrut
725   = mk_tuple_case uniqs (chunkify vars) body
726   where
727     mk_tuple_case us [vars] body
728       = mkSmallTupleCase vars body scrut_var scrut
729     mk_tuple_case us vars_s body
730       = let
731             (us', vars', body') = foldr one_tuple_case (us, [], body) vars_s
732         in
733         mk_tuple_case us' (chunkify vars') body'
734     one_tuple_case chunk_vars (us, vs, body)
735       = let
736             (us1, us2) = splitUniqSupply us
737             scrut_var = mkSysLocal FSLIT("ds") (uniqFromSupply us1)
738                         (mkCoreTupTy (map idType chunk_vars))
739             body' = mkSmallTupleCase chunk_vars body scrut_var (Var scrut_var)
740         in (us2, scrut_var:vs, body')
741 \end{code}
742
743 The same, but with a tuple small enough not to need nesting.
744
745 \begin{code}
746 mkSmallTupleCase
747         :: [Id]         -- the tuple args
748         -> CoreExpr     -- body of the case
749         -> Id           -- a variable of the same type as the scrutinee
750         -> CoreExpr     -- scrutinee
751         -> CoreExpr
752
753 mkSmallTupleCase [var] body _scrut_var scrut
754   = bindNonRec var scrut body
755 mkSmallTupleCase vars body scrut_var scrut
756   = Case scrut scrut_var [(DataAlt (tupleCon Boxed (length vars)), vars, body)]
757 \end{code}
758
759 %************************************************************************
760 %*                                                                      *
761 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
762 %*                                                                      *
763 %************************************************************************
764
765 Call the constructor Ids when building explicit lists, so that they
766 interact well with rules.
767
768 \begin{code}
769 mkNilExpr :: Type -> CoreExpr
770 mkNilExpr ty = mkConApp nilDataCon [Type ty]
771
772 mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
773 mkConsExpr ty hd tl = mkConApp consDataCon [Type ty, hd, tl]
774
775 mkListExpr :: Type -> [CoreExpr] -> CoreExpr
776 mkListExpr ty xs = foldr (mkConsExpr ty) (mkNilExpr ty) xs
777                             
778
779 -- The next three functions make tuple types, constructors and selectors,
780 -- with the rule that a 1-tuple is represented by the thing itselg
781 mkCoreTupTy :: [Type] -> Type
782 mkCoreTupTy [ty] = ty
783 mkCoreTupTy tys  = mkTupleTy Boxed (length tys) tys
784
785 mkCoreTup :: [CoreExpr] -> CoreExpr                         
786 -- Builds exactly the specified tuple.
787 -- No fancy business for big tuples
788 mkCoreTup []  = Var unitDataConId
789 mkCoreTup [c] = c
790 mkCoreTup cs  = mkConApp (tupleCon Boxed (length cs))
791                          (map (Type . exprType) cs ++ cs)
792
793 mkCoreSel :: [Id]       -- The tuple args
794           -> Id         -- The selected one
795           -> Id         -- A variable of the same type as the scrutinee
796           -> CoreExpr   -- Scrutinee
797           -> CoreExpr
798 -- mkCoreSel [x,y,z] x v e
799 -- ===>  case e of v { (x,y,z) -> x
800 mkCoreSel [var] should_be_the_same_var scrut_var scrut
801   = ASSERT(var == should_be_the_same_var)
802     scrut
803
804 mkCoreSel vars the_var scrut_var scrut
805   = ASSERT( notNull vars )
806     Case scrut scrut_var 
807          [(DataAlt (tupleCon Boxed (length vars)), vars, Var the_var)]
808 \end{code}
809
810
811 %************************************************************************
812 %*                                                                      *
813 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
814 %*                                                                      *
815 %************************************************************************
816
817 Generally, we handle pattern matching failure like this: let-bind a
818 fail-variable, and use that variable if the thing fails:
819 \begin{verbatim}
820         let fail.33 = error "Help"
821         in
822         case x of
823                 p1 -> ...
824                 p2 -> fail.33
825                 p3 -> fail.33
826                 p4 -> ...
827 \end{verbatim}
828 Then
829 \begin{itemize}
830 \item
831 If the case can't fail, then there'll be no mention of @fail.33@, and the
832 simplifier will later discard it.
833
834 \item
835 If it can fail in only one way, then the simplifier will inline it.
836
837 \item
838 Only if it is used more than once will the let-binding remain.
839 \end{itemize}
840
841 There's a problem when the result of the case expression is of
842 unboxed type.  Then the type of @fail.33@ is unboxed too, and
843 there is every chance that someone will change the let into a case:
844 \begin{verbatim}
845         case error "Help" of
846           fail.33 -> case ....
847 \end{verbatim}
848
849 which is of course utterly wrong.  Rather than drop the condition that
850 only boxed types can be let-bound, we just turn the fail into a function
851 for the primitive case:
852 \begin{verbatim}
853         let fail.33 :: Void -> Int#
854             fail.33 = \_ -> error "Help"
855         in
856         case x of
857                 p1 -> ...
858                 p2 -> fail.33 void
859                 p3 -> fail.33 void
860                 p4 -> ...
861 \end{verbatim}
862
863 Now @fail.33@ is a function, so it can be let-bound.
864
865 \begin{code}
866 mkFailurePair :: CoreExpr       -- Result type of the whole case expression
867               -> DsM (CoreBind, -- Binds the newly-created fail variable
868                                 -- to either the expression or \ _ -> expression
869                       CoreExpr) -- Either the fail variable, or fail variable
870                                 -- applied to unit tuple
871 mkFailurePair expr
872   | isUnLiftedType ty
873   = newFailLocalDs (unitTy `mkFunTy` ty)        `thenDs` \ fail_fun_var ->
874     newSysLocalDs unitTy                        `thenDs` \ fail_fun_arg ->
875     returnDs (NonRec fail_fun_var (Lam fail_fun_arg expr),
876               App (Var fail_fun_var) (Var unitDataConId))
877
878   | otherwise
879   = newFailLocalDs ty           `thenDs` \ fail_var ->
880     returnDs (NonRec fail_var expr, Var fail_var)
881   where
882     ty = exprType expr
883 \end{code}
884
885