[project @ 1997-06-05 21:03:17 by sof]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsUtils.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[DsUtils]{Utilities for desugaring}
5
6 This module exports some utility functions of no great interest.
7
8 \begin{code}
9 #include "HsVersions.h"
10
11 module DsUtils (
12         CanItFail(..), EquationInfo(..), MatchResult(..),
13
14         combineGRHSMatchResults,
15         combineMatchResults,
16         dsExprToAtom, SYN_IE(DsCoreArg),
17         mkCoAlgCaseMatchResult,
18         mkAppDs, mkConDs, mkPrimDs, mkErrorAppDs,
19         mkCoLetsMatchResult,
20         mkCoPrimCaseMatchResult,
21         mkFailurePair,
22         mkGuardedMatchResult,
23         mkSelectorBinds,
24         mkTupleBind,
25         mkTupleExpr,
26         mkTupleSelector,
27         selectMatchVars,
28         showForErr
29     ) where
30
31 IMP_Ubiq()
32 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ <= 201
33 IMPORT_DELOOPER(DsLoop)         ( match, matchSimply )
34 #else
35 import {-# SOURCE #-} Match (match, matchSimply )
36 #endif
37
38 import HsSyn            ( HsExpr(..), OutPat(..), HsLit(..), Fixity,
39                           Match, HsBinds, Stmt, DoOrListComp, HsType, ArithSeqInfo )
40 import TcHsSyn          ( SYN_IE(TypecheckedPat) )
41 import DsHsSyn          ( outPatType, collectTypedPatBinders )
42 import CmdLineOpts      ( opt_PprUserLength )
43 import CoreSyn
44
45 import DsMonad
46
47 import CoreUtils        ( coreExprType, mkCoreIfThenElse )
48 import PrelVals         ( iRREFUT_PAT_ERROR_ID, voidId )
49 import Pretty           ( Doc, hcat, text )
50 import Id               ( idType, dataConArgTys, 
51 --                        pprId{-ToDo:rm-},
52                           SYN_IE(DataCon), SYN_IE(DictVar), SYN_IE(Id), GenId )
53 import Literal          ( Literal(..) )
54 import PprType          ( GenType, GenTyVar )
55 import PrimOp           ( PrimOp )
56 import TyCon            ( isNewTyCon, tyConDataCons )
57 import Type             ( mkTyVarTys, mkRhoTy, mkForAllTys, mkFunTy,
58                           mkTheta, isUnboxedType, applyTyCon, getAppTyCon,
59                           GenType {- instances -}, SYN_IE(Type)
60                         )
61 import TyVar            ( GenTyVar {- instances -}, SYN_IE(TyVar) )
62 import TysPrim          ( voidTy )
63 import TysWiredIn       ( tupleTyCon, unitDataCon, tupleCon )
64 import UniqSet          ( mkUniqSet, minusUniqSet, uniqSetToList, SYN_IE(UniqSet) )
65 import Util             ( panic, assertPanic{-, pprTrace ToDo:rm-} )
66 import Unique           ( Unique )
67 import Usage            ( SYN_IE(UVar) )
68 import SrcLoc           ( SrcLoc {- instance Outputable -} )
69
70 import Outputable
71
72 \end{code}
73
74
75 %************************************************************************
76 %*                                                                      *
77 %* Selecting match variables
78 %*                                                                      *
79 %************************************************************************
80
81 We're about to match against some patterns.  We want to make some
82 @Ids@ to use as match variables.  If a pattern has an @Id@ readily at
83 hand, which should indeed be bound to the pattern as a whole, then use it;
84 otherwise, make one up.
85
86 \begin{code}
87 selectMatchVars :: [TypecheckedPat] -> DsM [Id]
88 selectMatchVars pats
89   = mapDs var_from_pat_maybe pats
90   where
91     var_from_pat_maybe (VarPat var)     = returnDs var
92     var_from_pat_maybe (AsPat var pat)  = returnDs var
93     var_from_pat_maybe (LazyPat pat)    = var_from_pat_maybe pat
94     var_from_pat_maybe other_pat
95       = newSysLocalDs (outPatType other_pat) -- OK, better make up one...
96 \end{code}
97
98
99 %************************************************************************
100 %*                                                                      *
101 %* type synonym EquationInfo and access functions for its pieces        *
102 %*                                                                      *
103 %************************************************************************
104 \subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
105
106 The ``equation info'' used by @match@ is relatively complicated and
107 worthy of a type synonym and a few handy functions.
108
109 \begin{code}
110 data EquationInfo
111   = EqnInfo
112         [TypecheckedPat]    -- the patterns for an eqn
113         MatchResult         -- Encapsulates the guards and bindings
114 \end{code}
115
116 \begin{code}
117 data MatchResult
118   = MatchResult
119         CanItFail
120         Type            -- Type of argument expression
121
122         (CoreExpr -> CoreExpr)
123                         -- Takes a expression to plug in at the
124                         -- failure point(s). The expression should
125                         -- be duplicatable!
126
127         DsMatchContext  -- The context info is used when producing warnings
128                         -- about shadowed patterns.  It's the context
129                         -- of the *first* thing matched in this group.
130                         -- Should perhaps be a list of them all!
131
132 data CanItFail = CanFail | CantFail
133
134 orFail CantFail CantFail = CantFail
135 orFail _        _        = CanFail
136
137
138 mkCoLetsMatchResult :: [CoreBinding] -> MatchResult -> MatchResult
139 mkCoLetsMatchResult binds (MatchResult can_it_fail ty body_fn cxt)
140   = MatchResult can_it_fail ty (\body -> mkCoLetsAny binds (body_fn body)) cxt
141
142 mkGuardedMatchResult :: CoreExpr -> MatchResult -> DsM MatchResult
143 mkGuardedMatchResult pred_expr (MatchResult can_it_fail ty body_fn cxt)
144   = returnDs (MatchResult CanFail
145                           ty
146                           (\fail -> mkCoreIfThenElse pred_expr (body_fn fail) fail)
147                           cxt
148     )
149
150 mkCoPrimCaseMatchResult :: Id                           -- Scrutinee
151                     -> [(Literal, MatchResult)] -- Alternatives
152                     -> DsM MatchResult
153 mkCoPrimCaseMatchResult var alts
154   = newSysLocalDs (idType var)  `thenDs` \ wild ->
155     returnDs (MatchResult CanFail
156                           ty1
157                           (mk_case alts wild)
158                           cxt1)
159   where
160     ((_,MatchResult _ ty1 _ cxt1) : _) = alts
161
162     mk_case alts wild fail_expr
163       = Case (Var var) (PrimAlts final_alts (BindDefault wild fail_expr))
164       where
165         final_alts = [ (lit, body_fn fail_expr)
166                      | (lit, MatchResult _ _ body_fn _) <- alts
167                      ]
168
169
170 mkCoAlgCaseMatchResult :: Id                            -- Scrutinee
171                     -> [(DataCon, [Id], MatchResult)]   -- Alternatives
172                     -> DsM MatchResult
173
174 mkCoAlgCaseMatchResult var alts
175   | isNewTyCon tycon            -- newtype case; use a let
176   = ASSERT( newtype_sanity )
177     returnDs (mkCoLetsMatchResult [coercion_bind] match_result)
178
179   | otherwise                   -- datatype case  
180   =         -- Find all the constructors in the type which aren't
181             -- explicitly mentioned in the alternatives:
182     case un_mentioned_constructors of
183         [] ->   -- All constructors mentioned, so no default needed
184                 returnDs (MatchResult can_any_alt_fail
185                                       ty1
186                                       (mk_case alts (\ignore -> NoDefault))
187                                       cxt1)
188
189         [con] ->     -- Just one constructor missing, so add a case for it
190                      -- We need to build new locals for the args of the constructor,
191                      -- and figuring out their types is somewhat tiresome.
192                 let
193                         arg_tys = dataConArgTys con tycon_arg_tys
194                 in
195                 newSysLocalsDs arg_tys  `thenDs` \ arg_ids ->
196
197                      -- Now we are ready to construct the new alternative
198                 let
199                         new_alt = (con, arg_ids, MatchResult CanFail ty1 id NoMatchContext)
200                 in
201                 returnDs (MatchResult CanFail
202                                       ty1
203                                       (mk_case (new_alt:alts) (\ignore -> NoDefault))
204                                       cxt1)
205
206         other ->      -- Many constructors missing, so use a default case
207                 newSysLocalDs scrut_ty          `thenDs` \ wild ->
208                 returnDs (MatchResult CanFail
209                                       ty1
210                                       (mk_case alts (\fail_expr -> BindDefault wild fail_expr))
211                                       cxt1)
212   where
213         -- Common stuff
214     scrut_ty = idType var
215     (tycon, tycon_arg_tys) = --pprTrace "CoAlgCase:" (pprType PprDebug scrut_ty) $ 
216                              getAppTyCon scrut_ty
217
218         -- Stuff for newtype
219     (con_id, arg_ids, match_result) = head alts
220     arg_id                          = head arg_ids
221     coercion_bind                   = NonRec arg_id (Coerce (CoerceOut con_id) 
222                                                             (idType arg_id)
223                                                             (Var var))
224     newtype_sanity                  = null (tail alts) && null (tail arg_ids)
225
226         -- Stuff for data types
227     data_cons = tyConDataCons tycon
228
229     un_mentioned_constructors
230       = uniqSetToList (mkUniqSet data_cons `minusUniqSet` mkUniqSet [ con | (con, _, _) <- alts] )
231
232     match_results = [match_result | (_,_,match_result) <- alts]
233     (MatchResult _ ty1 _ cxt1 : _) = match_results
234     can_any_alt_fail = foldr1 orFail [can_it_fail | MatchResult can_it_fail _ _ _ <- match_results]
235
236     mk_case alts deflt_fn fail_expr
237       = Case (Var var) (AlgAlts final_alts (deflt_fn fail_expr))
238       where
239         final_alts = [ (con, args, body_fn fail_expr)
240                      | (con, args, MatchResult _ _ body_fn _) <- alts
241                      ]
242
243
244 combineMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
245 combineMatchResults (MatchResult CanFail      ty1 body_fn1 cxt1)
246                     (MatchResult can_it_fail2 ty2 body_fn2 cxt2)
247   = mkFailurePair ty1           `thenDs` \ (bind_fn, duplicatable_expr) ->
248     let
249         new_body_fn1 = \body1 -> Let (bind_fn body1) (body_fn1 duplicatable_expr)
250         new_body_fn2 = \body2 -> new_body_fn1 (body_fn2 body2)
251     in
252     returnDs (MatchResult can_it_fail2 ty1 new_body_fn2 cxt1)
253
254 combineMatchResults match_result1@(MatchResult CantFail ty body_fn1 cxt1)
255                                   match_result2
256   = returnDs match_result1
257
258
259 -- The difference in combineGRHSMatchResults is that there is no
260 -- need to let-bind to avoid code duplication
261 combineGRHSMatchResults :: MatchResult -> MatchResult -> DsM MatchResult
262 combineGRHSMatchResults (MatchResult CanFail     ty1 body_fn1 cxt1)
263                         (MatchResult can_it_fail ty2 body_fn2 cxt2)
264   = returnDs (MatchResult can_it_fail ty1 (\ body -> body_fn1 (body_fn2 body)) cxt1)
265
266 combineGRHSMatchResults match_result1 match_result2
267   =     -- Delegate to avoid duplication of code
268     combineMatchResults match_result1 match_result2
269 \end{code}
270
271 %************************************************************************
272 %*                                                                      *
273 \subsection[dsExprToAtom]{Take an expression and produce an atom}
274 %*                                                                      *
275 %************************************************************************
276
277 \begin{code}
278 dsExprToAtom :: DsCoreArg                   -- The argument expression
279              -> (CoreArg -> DsM CoreExpr)   -- Something taking the argument *atom*,
280                                             -- and delivering an expression E
281              -> DsM CoreExpr                -- Either E or let x=arg-expr in E
282
283 dsExprToAtom (UsageArg u) continue_with = continue_with (UsageArg u)
284 dsExprToAtom (TyArg    t) continue_with = continue_with (TyArg    t)
285 dsExprToAtom (LitArg   l) continue_with = continue_with (LitArg   l)
286
287 dsExprToAtom (VarArg (Var v)) continue_with = continue_with (VarArg v)
288 dsExprToAtom (VarArg (Lit v)) continue_with = continue_with (LitArg v)
289
290 dsExprToAtom (VarArg arg_expr) continue_with
291   = let
292         ty = coreExprType arg_expr
293     in
294     newSysLocalDs ty                    `thenDs` \ arg_id ->
295     continue_with (VarArg arg_id)       `thenDs` \ body   ->
296     returnDs (
297         if isUnboxedType ty
298         then Case arg_expr (PrimAlts [] (BindDefault arg_id body))
299         else Let (NonRec arg_id arg_expr) body
300     )
301
302 dsExprsToAtoms :: [DsCoreArg]
303                -> ([CoreArg] -> DsM CoreExpr)
304                -> DsM CoreExpr
305
306 dsExprsToAtoms [] continue_with = continue_with []
307
308 dsExprsToAtoms (arg:args) continue_with
309   = dsExprToAtom   arg  $ \ arg_atom  ->
310     dsExprsToAtoms args $ \ arg_atoms ->
311     continue_with (arg_atom:arg_atoms)
312 \end{code}
313
314 %************************************************************************
315 %*                                                                      *
316 \subsection{Desugarer's versions of some Core functions}
317 %*                                                                      *
318 %************************************************************************
319
320 \begin{code}
321 type DsCoreArg = GenCoreArg CoreExpr{-NB!-} TyVar UVar
322
323 mkAppDs  :: CoreExpr -> [DsCoreArg] -> DsM CoreExpr
324 mkConDs  :: Id       -> [DsCoreArg] -> DsM CoreExpr
325 mkPrimDs :: PrimOp   -> [DsCoreArg] -> DsM CoreExpr
326
327 mkAppDs fun args
328   = dsExprsToAtoms args $ \ atoms ->
329     returnDs (mkGenApp fun atoms)
330
331 mkConDs con args
332   = dsExprsToAtoms args $ \ atoms ->
333     returnDs (Con  con atoms)
334
335 mkPrimDs op args
336   = dsExprsToAtoms args $ \ atoms ->
337     returnDs (Prim op  atoms)
338 \end{code}
339
340 \begin{code}
341 showForErr :: Outputable a => a -> String               -- Boring but useful
342 showForErr thing = show (ppr PprQuote thing)
343
344 mkErrorAppDs :: Id              -- The error function
345              -> Type            -- Type to which it should be applied
346              -> String          -- The error message string to pass
347              -> DsM CoreExpr
348
349 mkErrorAppDs err_id ty msg
350   = getSrcLocDs                 `thenDs` \ src_loc ->
351     let
352         full_msg = show (hcat [ppr (PprForUser opt_PprUserLength) src_loc, text "|", text msg])
353         msg_lit  = NoRepStr (_PK_ full_msg)
354     in
355     returnDs (mkApp (Var err_id) [] [ty] [LitArg msg_lit])
356 \end{code}
357
358 %************************************************************************
359 %*                                                                      *
360 \subsection[mkSelectorBind]{Make a selector bind}
361 %*                                                                      *
362 %************************************************************************
363
364 This is used in various places to do with lazy patterns.
365 For each binder $b$ in the pattern, we create a binding:
366
367     b = case v of pat' -> b'
368
369 where pat' is pat with each binder b cloned into b'.
370
371 ToDo: making these bindings should really depend on whether there's
372 much work to be done per binding.  If the pattern is complex, it
373 should be de-mangled once, into a tuple (and then selected from).
374 Otherwise the demangling can be in-line in the bindings (as here).
375
376 Boring!  Boring!  One error message per binder.  The above ToDo is
377 even more helpful.  Something very similar happens for pattern-bound
378 expressions.
379
380 \begin{code}
381 mkSelectorBinds :: TypecheckedPat       -- The pattern
382                 -> CoreExpr             -- Expression to which the pattern is bound
383                 -> DsM [(Id,CoreExpr)]
384
385 mkSelectorBinds (VarPat v) val_expr
386   = returnDs [(v, val_expr)]
387
388 mkSelectorBinds pat val_expr
389   | is_simple_tuple_pat pat 
390   = mkTupleBind binders val_expr
391
392   | otherwise
393   = mkErrorAppDs iRREFUT_PAT_ERROR_ID res_ty pat_string         `thenDs` \ error_msg ->
394     matchSimply val_expr pat res_ty local_tuple error_msg       `thenDs` \ tuple_expr ->
395     mkTupleBind binders tuple_expr
396
397   where
398     binders     = collectTypedPatBinders pat
399     local_tuple = mkTupleExpr binders
400     res_ty      = coreExprType local_tuple
401
402     is_simple_tuple_pat (TuplePat ps) = all is_var_pat ps
403     is_simple_tuple_pat other         = False
404
405     is_var_pat (VarPat v) = True
406     is_var_pat other      = False -- Even wild-card patterns aren't acceptable
407
408     pat_string = show (ppr (PprForUser opt_PprUserLength) pat)
409 \end{code}
410
411
412 \begin{code}
413 mkTupleBind :: [Id]                     -- Names of tuple components
414             -> CoreExpr                 -- Expr whose value is a tuple of correct type
415             -> DsM [(Id, CoreExpr)]     -- Bindings for the globals
416
417
418 mkTupleBind [local] tuple_expr
419   = returnDs [(local, tuple_expr)]
420
421 mkTupleBind locals tuple_expr
422   = newSysLocalDs (coreExprType tuple_expr)     `thenDs` \ tuple_var ->
423     let
424         mk_bind local = (local, mkTupleSelector locals local (Var tuple_var))
425     in
426     returnDs ( (tuple_var, tuple_expr) :
427                map mk_bind locals )
428 \end{code}
429
430
431 @mkTupleExpr@ builds a tuple; the inverse to @mkTupleSelector@.  If it
432 has only one element, it is the identity function.
433 \begin{code}
434 mkTupleExpr :: [Id] -> CoreExpr
435
436 mkTupleExpr []   = Con unitDataCon []
437 mkTupleExpr [id] = Var id
438 mkTupleExpr ids  = mkCon (tupleCon (length ids))
439                          [{-usages-}]
440                          (map idType ids)
441                          [ VarArg i | i <- ids ]
442 \end{code}
443
444
445 @mkTupleSelector@ builds a selector which scrutises the given
446 expression and extracts the one name from the list given.
447 If you want the no-shadowing rule to apply, the caller
448 is responsible for making sure that none of these names
449 are in scope.
450
451 If there is just one id in the ``tuple'', then the selector is
452 just the identity.
453
454 \begin{code}
455 mkTupleSelector :: [Id]                 -- The tuple args
456                 -> Id                   -- The selected one
457                 -> CoreExpr             -- Scrutinee
458                 -> CoreExpr
459
460 mkTupleSelector [] the_var scrut = panic "mkTupleSelector"
461
462 mkTupleSelector [var] should_be_the_same_var scrut
463   = ASSERT(var == should_be_the_same_var)
464     scrut
465
466 mkTupleSelector vars the_var scrut
467  = Case scrut (AlgAlts [(tupleCon arity, vars, Var the_var)]
468                           NoDefault)
469  where
470    arity = length vars
471 \end{code}
472
473
474 %************************************************************************
475 %*                                                                      *
476 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
477 %*                                                                      *
478 %************************************************************************
479
480 Generally, we handle pattern matching failure like this: let-bind a
481 fail-variable, and use that variable if the thing fails:
482 \begin{verbatim}
483         let fail.33 = error "Help"
484         in
485         case x of
486                 p1 -> ...
487                 p2 -> fail.33
488                 p3 -> fail.33
489                 p4 -> ...
490 \end{verbatim}
491 Then
492 \begin{itemize}
493 \item
494 If the case can't fail, then there'll be no mention of fail.33, and the
495 simplifier will later discard it.
496
497 \item
498 If it can fail in only one way, then the simplifier will inline it.
499
500 \item
501 Only if it is used more than once will the let-binding remain.
502 \end{itemize}
503
504 There's a problem when the result of the case expression is of
505 unboxed type.  Then the type of fail.33 is unboxed too, and
506 there is every chance that someone will change the let into a case:
507 \begin{verbatim}
508         case error "Help" of
509           fail.33 -> case ....
510 \end{verbatim}
511
512 which is of course utterly wrong.  Rather than drop the condition that
513 only boxed types can be let-bound, we just turn the fail into a function
514 for the primitive case:
515 \begin{verbatim}
516         let fail.33 :: Void -> Int#
517             fail.33 = \_ -> error "Help"
518         in
519         case x of
520                 p1 -> ...
521                 p2 -> fail.33 void
522                 p3 -> fail.33 void
523                 p4 -> ...
524 \end{verbatim}
525
526 Now fail.33 is a function, so it can be let-bound.
527
528 \begin{code}
529 mkFailurePair :: Type           -- Result type of the whole case expression
530               -> DsM (CoreExpr -> CoreBinding,
531                                 -- Binds the newly-created fail variable
532                                 -- to either the expression or \ _ -> expression
533                       CoreExpr) -- Either the fail variable, or fail variable
534                                 -- applied to unit tuple
535 mkFailurePair ty
536   | isUnboxedType ty
537   = newFailLocalDs (voidTy `mkFunTy` ty)        `thenDs` \ fail_fun_var ->
538     newSysLocalDs voidTy                        `thenDs` \ fail_fun_arg ->
539     returnDs (\ body ->
540                 NonRec fail_fun_var (Lam (ValBinder fail_fun_arg) body),
541               App (Var fail_fun_var) (VarArg voidId))
542
543   | otherwise
544   = newFailLocalDs ty           `thenDs` \ fail_var ->
545     returnDs (\ body -> NonRec fail_var body, Var fail_var)
546 \end{code}
547
548
549