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