7eab67f6e1a64a26363b17912b89a0ec9b18189d
[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,
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, mkCoreTupTy,
30         
31         dsReboundNames, lookupReboundName,
32
33         selectMatchVarL, 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          ( 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 SrcLoc           ( Located(..), unLoc, noLoc )
74 import Util             ( isSingleton, notNull, zipEqual )
75 import ListSetOps       ( assocDefault )
76 import FastString
77 \end{code}
78
79
80
81 %************************************************************************
82 %*                                                                      *
83                 Rebindable syntax
84 %*                                                                      *
85 %************************************************************************
86
87 \begin{code}
88 dsReboundNames :: ReboundNames Id 
89                -> DsM ([CoreBind],      -- Auxiliary bindings
90                        [(Name,Id)])     -- Maps the standard name to its value
91
92 dsReboundNames rebound_ids
93   = mapAndUnzipDs mk_bind rebound_ids   `thenDs` \ (binds_s, prs) ->
94     return (concat binds_s, prs)
95   where
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))
103
104 lookupReboundName :: [(Name,Id)] -> Name -> CoreExpr
105 lookupReboundName prs std_name
106   = Var (assocDefault (mk_panic std_name) prs std_name)
107   where
108     mk_panic std_name = pprPanic "dsReboundNames" (ptext SLIT("Not found:") <+> ppr std_name)
109 \end{code}
110
111
112 %************************************************************************
113 %*                                                                      *
114 \subsection{Tidying lit pats}
115 %*                                                                      *
116 %************************************************************************
117
118 \begin{code}
119 tidyLitPat :: HsLit -> LPat Id -> LPat Id
120 tidyLitPat (HsChar c) pat = mkCharLitPat c
121 tidyLitPat lit        pat = pat
122
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!
130   where
131
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
137
138   where
139     mk_int    (HsInteger i _) = HsIntPrim i
140
141     mk_float  (HsInteger i _) = HsFloatPrim (fromInteger i)
142     mk_float  (HsRat f _)     = HsFloatPrim f
143
144     mk_double (HsInteger i _) = HsDoublePrim (fromInteger i)
145     mk_double (HsRat f _)     = HsDoublePrim f
146 \end{code}
147
148
149 %************************************************************************
150 %*                                                                      *
151 \subsection{Building lets}
152 %*                                                                      *
153 %************************************************************************
154
155 Use case, not let for unlifted types.  The simplifier will turn some
156 back again.
157
158 \begin{code}
159 mkDsLet :: CoreBind -> CoreExpr -> CoreExpr
160 mkDsLet (NonRec bndr rhs) body
161   | isUnLiftedType (idType bndr) = Case rhs bndr [(DEFAULT,[],body)]
162 mkDsLet bind body
163   = Let bind body
164
165 mkDsLets :: [CoreBind] -> CoreExpr -> CoreExpr
166 mkDsLets binds body = foldr mkDsLet body binds
167 \end{code}
168
169
170 %************************************************************************
171 %*                                                                      *
172 \subsection{ Selecting match variables}
173 %*                                                                      *
174 %************************************************************************
175
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.
180
181 \begin{code}
182 selectMatchVarL :: LPat Id -> DsM Id
183 selectMatchVarL pat = selectMatchVar (unLoc pat)
184
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...
190 \end{code}
191
192
193 %************************************************************************
194 %*                                                                      *
195 %* type synonym EquationInfo and access functions for its pieces        *
196 %*                                                                      *
197 %************************************************************************
198 \subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
199
200 The ``equation info'' used by @match@ is relatively complicated and
201 worthy of a type synonym and a few handy functions.
202
203 \begin{code}
204
205 type EqnNo   = Int
206 type EqnSet  = UniqSet EqnNo
207
208 data EquationInfo
209   = EqnInfo
210         EqnNo           -- The number of the equation
211
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!
216
217         [Pat Id]        -- The patterns for an eqn
218
219         MatchResult         -- Encapsulates the guards and bindings
220 \end{code}
221
222 \begin{code}
223 data MatchResult
224   = MatchResult
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
229                         -- be duplicatable!
230
231 data CanItFail = CanFail | CantFail
232
233 orFail CantFail CantFail = CantFail
234 orFail _        _        = CanFail
235 \end{code}
236
237 Functions on MatchResults
238
239 \begin{code}
240 cantFailMatchResult :: CoreExpr -> MatchResult
241 cantFailMatchResult expr = MatchResult CantFail (\ ignore -> returnDs expr)
242
243 extractMatchResult :: MatchResult -> CoreExpr -> DsM CoreExpr
244 extractMatchResult (MatchResult CantFail match_fn) fail_expr
245   = match_fn (error "It can't fail!")
246
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)
251
252
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
257   where
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)
262
263 combineMatchResults match_result1@(MatchResult CantFail body_fn1) match_result2
264   = match_result1
265
266
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))
271
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 ->
275                                       encl_fn body)
276
277
278 mkCoLetsMatchResult :: [CoreBind] -> MatchResult -> MatchResult
279 mkCoLetsMatchResult binds match_result
280   = adjustMatchResult (mkDsLets binds) match_result
281
282
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))
287
288 mkCoPrimCaseMatchResult :: Id                           -- Scrutinee
289                     -> [(Literal, MatchResult)]         -- Alternatives
290                     -> MatchResult
291 mkCoPrimCaseMatchResult var match_alts
292   = MatchResult CanFail mk_case
293   where
294     mk_case fail
295       = mappM (mk_alt fail) match_alts          `thenDs` \ alts ->
296         returnDs (Case (Var var) var ((DEFAULT, [], fail) : alts))
297
298     mk_alt fail (lit, MatchResult _ body_fn) = body_fn fail     `thenDs` \ body ->
299                                                returnDs (LitAlt lit, [], body)
300
301
302 mkCoAlgCaseMatchResult :: Id                                    -- Scrutinee
303                     -> [(DataCon, [CoreBndr], MatchResult)]     -- Alternatives
304                     -> MatchResult
305
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
310
311   | isPArrFakeAlts match_alts   -- Sugared parallel array; use a literal case 
312   = MatchResult CanFail mk_parrCase
313
314   | otherwise                   -- Datatype case; use a case
315   = MatchResult fail_flag mk_case
316   where
317         -- Common stuff
318     scrut_ty = idType var
319     tycon    = tcTyConAppTyCon scrut_ty         -- Newtypes must be opaque here
320
321         -- Stuff for newtype
322     (_, arg_ids, match_result) = head match_alts
323     arg_id                     = head arg_ids
324     newtype_rhs                = mkNewTypeBody tycon (idType arg_id) (Var var)
325                 
326         -- Stuff for data types
327     data_cons      = tyConDataCons tycon
328     match_results  = [match_result | (_,_,match_result) <- match_alts]
329
330     fail_flag | exhaustive_case
331               = foldr1 orFail [can_it_fail | MatchResult can_it_fail _ <- match_results]
332               | otherwise
333               = CanFail
334
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))
338
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)
343
344     mk_default fail | exhaustive_case = []
345                     | otherwise       = [(DEFAULT, [], fail)]
346
347     un_mentioned_constructors
348         = mkUniqSet data_cons `minusUniqSet` mkUniqSet [ con | (con, _, _) <- match_alts]
349     exhaustive_case = isEmptyUniqSet un_mentioned_constructors
350
351         -- Stuff for parallel arrays
352         -- 
353         -- * the following is to desugar cases over fake constructors for
354         --   parallel arrays, which are introduced by `tidy1' in the `PArrPat'
355         --   case
356         --
357         -- Concerning `isPArrFakeAlts':
358         --
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)
364         --
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.
372         --
373     isPArrFakeAlts [(dcon, _, _)]      = isPArrFakeCon dcon
374     isPArrFakeAlts ((dcon, _, _):alts) = 
375       case (isPArrFakeCon dcon, isPArrFakeAlts alts) of
376         (True , True ) -> True
377         (False, False) -> False
378         _              -> 
379           panic "DsUtils: You may not mix `[:...:]' with `PArr' patterns"
380     --
381     mk_parrCase fail =             
382       dsLookupGlobalId lengthPName                      `thenDs` \lengthP  ->
383       unboxAlt                                          `thenDs` \alt      ->
384       returnDs (Case (len lengthP) (mkWildId intTy) [alt])
385       where
386         elemTy      = case splitTyConApp (idType var) of
387                         (_, [elemTy]) -> elemTy
388                         _               -> panic panicMsg
389         panicMsg    = "DsUtils.mkCoAlgCaseMatchResult: not a parallel array?"
390         len lengthP = mkApps (Var lengthP) [Type elemTy, Var var]
391         --
392         unboxAlt = 
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)))
397           where
398             wild = mkWildId intPrimTy
399             dft  = (DEFAULT, [], fail)
400         --
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
405         -- with the first
406         --
407         mkAlt indexP (con, args, MatchResult _ bodyFun) = 
408           bodyFun fail                                  `thenDs` \body     ->
409           returnDs (LitAlt lit, [], mkDsLets binds body)
410           where
411             lit   = MachInt $ toInteger (dataConSourceArity con)
412             binds = [NonRec arg (indexExpr i) | (i, arg) <- zip [1..] args]
413             --
414             indexExpr i = mkApps (Var indexP) [Type elemTy, Var var, mkIntExpr i]
415 \end{code}
416
417
418 %************************************************************************
419 %*                                                                      *
420 \subsection{Desugarer's versions of some Core functions}
421 %*                                                                      *
422 %************************************************************************
423
424 \begin{code}
425 mkErrorAppDs :: Id              -- The error function
426              -> Type            -- Type to which it should be applied
427              -> String          -- The error message string to pass
428              -> DsM CoreExpr
429
430 mkErrorAppDs err_id ty msg
431   = getSrcSpanDs                `thenDs` \ src_loc ->
432     let
433         full_msg = showSDoc (hcat [ppr src_loc, text "|", text msg])
434         core_msg = Lit (MachStr (mkFastString (stringToUtf8 full_msg)))
435     in
436     returnDs (mkApps (Var err_id) [Type ty, core_msg])
437 \end{code}
438
439
440 *************************************************************
441 %*                                                                      *
442 \subsection{Making literals}
443 %*                                                                      *
444 %************************************************************************
445
446 \begin{code}
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
452
453 mkIntExpr  i = mkConApp intDataCon  [mkIntLit i]
454 mkCharExpr c = mkConApp charDataCon [mkLit (MachChar c)]
455
456 mkIntegerExpr i
457   | inIntRange i        -- Small enough, so start from an Int
458   = dsLookupDataCon  smallIntegerDataConName    `thenDs` \ integer_dc ->
459     returnDs (mkSmallIntegerLit integer_dc i)
460
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.
464
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 ->
469     let 
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
473
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 
477                                   then lit 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)
481                    where
482                      (q,r) = i `quotRem` b
483
484     in
485     returnDs (horner tARGET_MAX_INT i)
486
487 mkSmallIntegerLit small_integer_data_con i = mkConApp small_integer_data_con [mkIntLit i]
488
489 mkStringLit str = mkStringLitFS (mkFastString str)
490
491 mkStringLitFS str
492   | nullFastString str
493   = returnDs (mkNilExpr charTy)
494
495   | lengthFS str == 1
496   = let
497         the_char = mkCharExpr (headFS str)
498     in
499     returnDs (mkConsExpr charTy the_char (mkNilExpr charTy))
500
501   | all safeChar int_chars
502   = dsLookupGlobalId unpackCStringName  `thenDs` \ unpack_id ->
503     returnDs (App (Var unpack_id) (Lit (MachStr str)))
504
505   | otherwise
506   = dsLookupGlobalId unpackCStringUtf8Name      `thenDs` \ unpack_id ->
507     returnDs (App (Var unpack_id) (Lit (MachStr (mkFastString (intsToUtf8 int_chars)))))
508
509   where
510     int_chars = unpackIntFS str
511     safeChar c = c >= 1 && c <= 0xFF
512 \end{code}
513
514
515 %************************************************************************
516 %*                                                                      *
517 \subsection[mkSelectorBind]{Make a selector bind}
518 %*                                                                      *
519 %************************************************************************
520
521 This is used in various places to do with lazy patterns.
522 For each binder $b$ in the pattern, we create a binding:
523 \begin{verbatim}
524     b = case v of pat' -> b'
525 \end{verbatim}
526 where @pat'@ is @pat@ with each binder @b@ cloned into @b'@.
527
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).
532
533 Boring!  Boring!  One error message per binder.  The above ToDo is
534 even more helpful.  Something very similar happens for pattern-bound
535 expressions.
536
537 \begin{code}
538 mkSelectorBinds :: LPat Id      -- The pattern
539                 -> CoreExpr     -- Expression to which the pattern is bound
540                 -> DsM [(Id,CoreExpr)]
541
542 mkSelectorBinds (L _ (VarPat v)) val_expr
543   = returnDs [(v, val_expr)]
544
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
552
553         -- Make up 'v'
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
557         --      (x,y) = ?i
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) => ...)
562         --
563         -- So to get the type of 'v', use the pattern not the rhs.  Often more
564         -- efficient too.
565     newSysLocalDs (hsPatType pat)       `thenDs` \ val_var ->
566
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) :
575                binds )
576
577
578   | otherwise
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 ->
583     let
584         mk_tup_bind binder
585           = (binder, mkTupleSelector binders binder tuple_var (Var tuple_var))
586     in
587     returnDs ( (tuple_var, tuple_expr) : map mk_tup_bind binders )
588   where
589     binders     = collectPatBinders pat
590     local_tuple = mkTupleExpr binders
591     tuple_ty    = exprType local_tuple
592
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)
600       where
601         error_expr = mkCoerce (idType bndr_var) (Var err_var)
602
603     is_simple_lpat p = is_simple_pat (unLoc p)
604
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
610
611     is_triv_lpat p = is_triv_pat (unLoc p)
612
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
617 \end{code}
618
619
620 %************************************************************************
621 %*                                                                      *
622                 Tuples
623 %*                                                                      *
624 %************************************************************************
625
626 @mkTupleExpr@ builds a tuple; the inverse to @mkTupleSelector@.  
627
628 * If it has only one element, it is the identity function.
629
630 * If there are more elements than a big tuple can have, it nests 
631   the tuples.  
632
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.
635
636 \begin{code}
637 mkTupleExpr :: [Id] -> CoreExpr
638 mkTupleExpr ids = mkBigCoreTup (map Var ids)
639
640 -- corresponding type
641 mkTupleType :: [Id] -> Type
642 mkTupleType ids = mkBigTuple mkCoreTupTy (map idType ids)
643
644 mkBigCoreTup :: [CoreExpr] -> CoreExpr
645 mkBigCoreTup = mkBigTuple mkCoreTup
646
647 mkBigTuple :: ([a] -> a) -> [a] -> a
648 mkBigTuple small_tuple as = mk_big_tuple (chunkify as)
649   where
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))
653
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
657 chunkify xs
658   | n_xs <= mAX_TUPLE_SIZE = {- pprTrace "Small" (ppr n_xs) -} [xs] 
659   | otherwise              = {- pprTrace "Big"   (ppr n_xs) -} (split xs)
660   where
661     n_xs     = length xs
662     split [] = []
663     split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
664 \end{code}
665
666
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
671 are in scope.
672
673 If there is just one id in the ``tuple'', then the selector is
674 just the identity.
675
676 If it's big, it does nesting
677         mkTupleSelector [a,b,c,d] b v e
678           = case e of v { 
679                 (p,q) -> case p of p {
680                            (a,b) -> b }}
681 We use 'tpl' vars for the p,q, since shadowing does not matter.
682
683 In fact, it's more convenient to generate it innermost first, getting
684
685         case (case e of v 
686                 (p,q) -> p) of p
687           (a,b) -> b
688
689 \begin{code}
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
694                 -> CoreExpr
695
696 mkTupleSelector vars the_var scrut_var scrut
697   = mk_tup_sel (chunkify vars) the_var
698   where
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
702         where
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,
706                                          the_var `elem` gp ]
707 \end{code}
708
709 A generalization of @mkTupleSelector@, allowing the body
710 of the case to be an arbitrary expression.
711
712 If the tuple is big, it is nested:
713
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) ->
718             body }}}
719
720 To avoid shadowing, we use uniqs to invent new variables p,q.
721
722 ToDo: eliminate cases where none of the variables are needed.
723
724 \begin{code}
725 mkTupleCase
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
731         -> CoreExpr
732
733 mkTupleCase uniqs vars body scrut_var scrut
734   = mk_tuple_case uniqs (chunkify vars) body
735   where
736     mk_tuple_case us [vars] body
737       = mkSmallTupleCase vars body scrut_var scrut
738     mk_tuple_case us vars_s body
739       = let
740             (us', vars', body') = foldr one_tuple_case (us, [], body) vars_s
741         in
742         mk_tuple_case us' (chunkify vars') body'
743     one_tuple_case chunk_vars (us, vs, body)
744       = let
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')
750 \end{code}
751
752 The same, but with a tuple small enough not to need nesting.
753
754 \begin{code}
755 mkSmallTupleCase
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
760         -> CoreExpr
761
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)]
766 \end{code}
767
768 %************************************************************************
769 %*                                                                      *
770 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
771 %*                                                                      *
772 %************************************************************************
773
774 Call the constructor Ids when building explicit lists, so that they
775 interact well with rules.
776
777 \begin{code}
778 mkNilExpr :: Type -> CoreExpr
779 mkNilExpr ty = mkConApp nilDataCon [Type ty]
780
781 mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
782 mkConsExpr ty hd tl = mkConApp consDataCon [Type ty, hd, tl]
783
784 mkListExpr :: Type -> [CoreExpr] -> CoreExpr
785 mkListExpr ty xs = foldr (mkConsExpr ty) (mkNilExpr ty) xs
786                             
787
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
793
794 mkCoreTup :: [CoreExpr] -> CoreExpr                         
795 -- Builds exactly the specified tuple.
796 -- No fancy business for big tuples
797 mkCoreTup []  = Var unitDataConId
798 mkCoreTup [c] = c
799 mkCoreTup cs  = mkConApp (tupleCon Boxed (length cs))
800                          (map (Type . exprType) cs ++ cs)
801
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
806           -> CoreExpr
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)
811     scrut
812
813 mkCoreSel vars the_var scrut_var scrut
814   = ASSERT( notNull vars )
815     Case scrut scrut_var 
816          [(DataAlt (tupleCon Boxed (length vars)), vars, Var the_var)]
817 \end{code}
818
819
820 %************************************************************************
821 %*                                                                      *
822 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
823 %*                                                                      *
824 %************************************************************************
825
826 Generally, we handle pattern matching failure like this: let-bind a
827 fail-variable, and use that variable if the thing fails:
828 \begin{verbatim}
829         let fail.33 = error "Help"
830         in
831         case x of
832                 p1 -> ...
833                 p2 -> fail.33
834                 p3 -> fail.33
835                 p4 -> ...
836 \end{verbatim}
837 Then
838 \begin{itemize}
839 \item
840 If the case can't fail, then there'll be no mention of @fail.33@, and the
841 simplifier will later discard it.
842
843 \item
844 If it can fail in only one way, then the simplifier will inline it.
845
846 \item
847 Only if it is used more than once will the let-binding remain.
848 \end{itemize}
849
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:
853 \begin{verbatim}
854         case error "Help" of
855           fail.33 -> case ....
856 \end{verbatim}
857
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:
861 \begin{verbatim}
862         let fail.33 :: Void -> Int#
863             fail.33 = \_ -> error "Help"
864         in
865         case x of
866                 p1 -> ...
867                 p2 -> fail.33 void
868                 p3 -> fail.33 void
869                 p4 -> ...
870 \end{verbatim}
871
872 Now @fail.33@ is a function, so it can be let-bound.
873
874 \begin{code}
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
880 mkFailurePair expr
881   | isUnLiftedType ty
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))
886
887   | otherwise
888   = newFailLocalDs ty           `thenDs` \ fail_var ->
889     returnDs (NonRec fail_var expr, Var fail_var)
890   where
891     ty = exprType expr
892 \end{code}
893
894