[project @ 1998-12-18 17:40:31 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsExpr.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[DsExpr]{Matching expressions (Exprs)}
5
6 \begin{code}
7 module DsExpr ( dsExpr, dsLet ) where
8
9 #include "HsVersions.h"
10
11
12 import HsSyn            ( failureFreePat,
13                           HsExpr(..), OutPat(..), HsLit(..), ArithSeqInfo(..),
14                           Stmt(..), StmtCtxt(..), Match(..), HsBinds(..), MonoBinds(..), 
15                           mkSimpleMatch
16                         )
17 import TcHsSyn          ( TypecheckedHsExpr, TypecheckedHsBinds,
18                           TypecheckedStmt,
19                           maybeBoxedPrimType
20
21                         )
22 import CoreSyn
23
24 import DsMonad
25 import DsBinds          ( dsMonoBinds )
26 import DsGRHSs          ( dsGuarded )
27 import DsCCall          ( dsCCall )
28 import DsListComp       ( dsListComp )
29 import DsUtils          ( mkErrorAppDs )
30 import Match            ( matchWrapper, matchSimply )
31
32 import CoreUtils        ( coreExprType )
33 import CostCentre       ( mkUserCC )
34 import FieldLabel       ( FieldLabel )
35 import Id               ( Id, idType, recordSelectorFieldLabel )
36 import Const            ( Con(..) )
37 import DataCon          ( DataCon, dataConId, dataConTyCon, dataConArgTys, dataConFieldLabels )
38 import Const            ( mkMachInt, Literal(..) )
39 import PrelVals         ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID )
40 import TyCon            ( isNewTyCon )
41 import DataCon          ( isExistentialDataCon )
42 import Type             ( splitFunTys, mkTyConApp,
43                           splitAlgTyConApp, splitTyConApp_maybe,
44                           splitAppTy, isUnLiftedType, Type
45                         )
46 import TysWiredIn       ( tupleCon, unboxedTupleCon,
47                           consDataCon, listTyCon, mkListTy,
48                           charDataCon, charTy, stringTy
49                         )
50 import BasicTypes       ( RecFlag(..) )
51 import Maybes           ( maybeToBool )
52 import Util             ( zipEqual, zipWithEqual )
53 import Outputable
54 \end{code}
55
56
57 %************************************************************************
58 %*                                                                      *
59 \subsection{dsLet}
60 %*                                                                      *
61 %************************************************************************
62
63 @dsLet@ is a match-result transformer, taking the MatchResult for the body
64 and transforming it into one for the let-bindings enclosing the body.
65
66 This may seem a bit odd, but (source) let bindings can contain unboxed
67 binds like
68
69         C x# = e
70
71 This must be transformed to a case expression and, if the type has
72 more than one constructor, may fail.
73
74 \begin{code}
75 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
76
77 dsLet EmptyBinds body
78   = returnDs body
79
80 dsLet (ThenBinds b1 b2) body
81   = dsLet b2 body       `thenDs` \ body' ->
82     dsLet b1 body'
83   
84 -- Special case for bindings which bind unlifted variables
85 dsLet (MonoBind (AbsBinds [] [] binder_triples (PatMonoBind pat grhss loc)) sigs is_rec) body
86   | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
87   = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
88     putSrcLocDs loc                     $
89     dsGuarded grhss                     `thenDs` \ rhs ->
90     let
91         body' = foldr bind body binder_triples
92         bind (tyvars, g, l) body = ASSERT( null tyvars )
93                                    bindNonRec g (Var l) body
94     in
95     mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat))    `thenDs` \ error_expr ->
96     matchSimply rhs PatBindMatch pat body' error_expr
97   where
98     result_ty = coreExprType body
99
100 -- Ordinary case for bindings
101 dsLet (MonoBind binds sigs is_rec) body
102   = dsMonoBinds False binds []  `thenDs` \ prs ->
103     case is_rec of
104       Recursive    -> returnDs (Let (Rec prs) body)
105       NonRecursive -> returnDs (foldr mk_let body prs)
106   where
107     mk_let (bndr,rhs) body = Let (NonRec bndr rhs) body
108 \end{code}
109
110 %************************************************************************
111 %*                                                                      *
112 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
113 %*                                                                      *
114 %************************************************************************
115
116 \begin{code}
117 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
118
119 dsExpr e@(HsVar var) = returnDs (Var var)
120 \end{code}
121
122 %************************************************************************
123 %*                                                                      *
124 \subsection[DsExpr-literals]{Literals}
125 %*                                                                      *
126 %************************************************************************
127
128 We give int/float literals type Integer and Rational, respectively.
129 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
130 around them.
131
132 ToDo: put in range checks for when converting "i"
133 (or should that be in the typechecker?)
134
135 For numeric literals, we try to detect there use at a standard type
136 (Int, Float, etc.) are directly put in the right constructor.
137 [NB: down with the @App@ conversion.]
138 Otherwise, we punt, putting in a "NoRep" Core literal (where the
139 representation decisions are delayed)...
140
141 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
142
143 \begin{code}
144 dsExpr (HsLitOut (HsString s) _)
145   | _NULL_ s
146   = returnDs (mkNilExpr charTy)
147
148   | _LENGTH_ s == 1
149   = let
150         the_char = mkConApp charDataCon [mkLit (MachChar (_HEAD_ s))]
151         the_nil  = mkNilExpr charTy
152         the_cons = mkConApp consDataCon [Type charTy, the_char, the_nil]
153     in
154     returnDs the_cons
155
156
157 -- "_" => build (\ c n -> c 'c' n)      -- LATER
158
159 -- "str" ==> build (\ c n -> foldr charTy T c n "str")
160
161 {- LATER:
162 dsExpr (HsLitOut (HsString str) _)
163   = newTyVarsDs [alphaTyVar]            `thenDs` \ [new_tyvar] ->
164     let
165         new_ty = mkTyVarTy new_tyvar
166     in
167     newSysLocalsDs [
168                 charTy `mkFunTy` (new_ty `mkFunTy` new_ty),
169                 new_ty,
170                        mkForallTy [alphaTyVar]
171                                ((charTy `mkFunTy` (alphaTy `mkFunTy` alphaTy))
172                                         `mkFunTy` (alphaTy `mkFunTy` alphaTy))
173                 ]                       `thenDs` \ [c,n,g] ->
174      returnDs (mkBuild charTy new_tyvar c n g (
175         foldl App
176           (CoTyApp (CoTyApp (Var foldrId) charTy) new_ty) *** ensure non-prim type ***
177           [VarArg c,VarArg n,LitArg (NoRepStr str)]))
178 -}
179
180 -- otherwise, leave it as a NoRepStr;
181 -- the Core-to-STG pass will wrap it in an application of "unpackCStringId".
182
183 dsExpr (HsLitOut (HsString str) _)
184   = returnDs (mkLit (NoRepStr str stringTy))
185
186 dsExpr (HsLitOut (HsLitLit str) ty)
187   = returnDs ( mkConApp data_con [mkLit (MachLitLit str prim_ty)] )
188   where
189     (data_con, prim_ty)
190       = case (maybeBoxedPrimType ty) of
191           Just (boxing_data_con, prim_ty) -> (boxing_data_con, prim_ty)
192           Nothing
193             -> pprPanic "ERROR: ``literal-literal'' not a single-constructor type: "
194                         (hcat [ptext str, text "; type: ", ppr ty])
195
196 dsExpr (HsLitOut (HsInt i) ty)
197   = returnDs (mkLit (NoRepInteger i ty))
198
199 dsExpr (HsLitOut (HsFrac r) ty)
200   = returnDs (mkLit (NoRepRational r ty))
201
202 -- others where we know what to do:
203
204 dsExpr (HsLitOut (HsIntPrim i) _)
205   | (i >= toInteger minInt && i <= toInteger maxInt) 
206   = returnDs (mkLit (mkMachInt i))
207   | otherwise
208   = error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
209
210 dsExpr (HsLitOut (HsFloatPrim f) _)
211   = returnDs (mkLit (MachFloat f))
212     -- ToDo: range checking needed!
213
214 dsExpr (HsLitOut (HsDoublePrim d) _)
215   = returnDs (mkLit (MachDouble d))
216     -- ToDo: range checking needed!
217
218 dsExpr (HsLitOut (HsChar c) _)
219   = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
220
221 dsExpr (HsLitOut (HsCharPrim c) _)
222   = returnDs (mkLit (MachChar c))
223
224 dsExpr (HsLitOut (HsStringPrim s) _)
225   = returnDs (mkLit (MachStr s))
226
227 -- end of literals magic. --
228
229 dsExpr expr@(HsLam a_Match)
230   = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
231     returnDs (mkLams binders matching_code)
232
233 dsExpr expr@(HsApp fun arg)      
234   = dsExpr fun          `thenDs` \ core_fun ->
235     dsExpr arg          `thenDs` \ core_arg ->
236     returnDs (core_fun `App` core_arg)
237
238 \end{code}
239
240 Operator sections.  At first it looks as if we can convert
241 \begin{verbatim}
242         (expr op)
243 \end{verbatim}
244 to
245 \begin{verbatim}
246         \x -> op expr x
247 \end{verbatim}
248
249 But no!  expr might be a redex, and we can lose laziness badly this
250 way.  Consider
251 \begin{verbatim}
252         map (expr op) xs
253 \end{verbatim}
254 for example.  So we convert instead to
255 \begin{verbatim}
256         let y = expr in \x -> op y x
257 \end{verbatim}
258 If \tr{expr} is actually just a variable, say, then the simplifier
259 will sort it out.
260
261 \begin{code}
262 dsExpr (OpApp e1 op _ e2)
263   = dsExpr op                                           `thenDs` \ core_op ->
264     -- for the type of y, we need the type of op's 2nd argument
265     let
266         (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
267     in
268     dsExpr e1                           `thenDs` \ x_core ->
269     dsExpr e2                           `thenDs` \ y_core ->
270     returnDs (mkApps core_op [x_core, y_core])
271     
272 dsExpr (SectionL expr op)
273   = dsExpr op                                           `thenDs` \ core_op ->
274     -- for the type of y, we need the type of op's 2nd argument
275     let
276         (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
277     in
278     dsExpr expr                         `thenDs` \ x_core ->
279     newSysLocalDs x_ty                  `thenDs` \ x_id ->
280     newSysLocalDs y_ty                  `thenDs` \ y_id ->
281
282     returnDs (bindNonRec x_id x_core $
283               Lam y_id (mkApps core_op [Var x_id, Var y_id]))
284
285 -- dsExpr (SectionR op expr)    -- \ x -> op x expr
286 dsExpr (SectionR op expr)
287   = dsExpr op                   `thenDs` \ core_op ->
288     -- for the type of x, we need the type of op's 2nd argument
289     let
290         (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
291     in
292     dsExpr expr                         `thenDs` \ y_core ->
293     newSysLocalDs x_ty                  `thenDs` \ x_id ->
294     newSysLocalDs y_ty                  `thenDs` \ y_id ->
295
296     returnDs (bindNonRec y_id y_core $
297               Lam x_id (mkApps core_op [Var x_id, Var y_id]))
298
299 dsExpr (CCall label args may_gc is_asm result_ty)
300   = mapDs dsExpr args           `thenDs` \ core_args ->
301     dsCCall label core_args may_gc is_asm result_ty
302         -- dsCCall does all the unboxification, etc.
303
304 dsExpr (HsSCC cc expr)
305   = dsExpr expr                 `thenDs` \ core_expr ->
306     getModuleAndGroupDs         `thenDs` \ (mod_name, group_name) ->
307     returnDs (Note (SCC (mkUserCC cc mod_name group_name)) core_expr)
308
309 -- special case to handle unboxed tuple patterns
310
311 dsExpr (HsCase discrim matches@[Match _ [TuplePat ps boxed] _ _] src_loc)
312  | all var_pat ps 
313  =  putSrcLocDs src_loc $
314     dsExpr discrim                              `thenDs` \ core_discrim ->
315     matchWrapper CaseMatch matches "case"       `thenDs` \ ([discrim_var], matching_code) ->
316     case matching_code of
317         Case (Var x) bndr alts | x == discrim_var -> 
318                 returnDs (Case core_discrim bndr alts)
319         _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
320
321 dsExpr (HsCase discrim matches src_loc)
322   = putSrcLocDs src_loc $
323     dsExpr discrim                              `thenDs` \ core_discrim ->
324     matchWrapper CaseMatch matches "case"       `thenDs` \ ([discrim_var], matching_code) ->
325     returnDs (bindNonRec discrim_var core_discrim matching_code)
326
327 dsExpr (HsLet binds body)
328   = dsExpr body         `thenDs` \ body' ->
329     dsLet binds body'
330     
331 dsExpr (HsDoOut do_or_lc stmts return_id then_id zero_id result_ty src_loc)
332   | maybeToBool maybe_list_comp
333   =     -- Special case for list comprehensions
334     putSrcLocDs src_loc $
335     dsListComp stmts elt_ty
336
337   | otherwise
338   = putSrcLocDs src_loc $
339     dsDo do_or_lc stmts return_id then_id zero_id result_ty
340   where
341     maybe_list_comp 
342         = case (do_or_lc, splitTyConApp_maybe result_ty) of
343             (ListComp, Just (tycon, [elt_ty]))
344                   | tycon == listTyCon
345                  -> Just elt_ty
346             other -> Nothing
347         -- We need the ListComp form to use deListComp (rather than the "do" form)
348         -- because the "return" in a do block is a call to "PrelBase.return", and
349         -- not a ReturnStmt.  Only the ListComp form has ReturnStmts
350
351     Just elt_ty = maybe_list_comp
352
353 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
354   = putSrcLocDs src_loc $
355     dsExpr guard_expr   `thenDs` \ core_guard ->
356     dsExpr then_expr    `thenDs` \ core_then ->
357     dsExpr else_expr    `thenDs` \ core_else ->
358     returnDs (mkIfThenElse core_guard core_then core_else)
359 \end{code}
360
361
362 Type lambda and application
363 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
364 \begin{code}
365 dsExpr (TyLam tyvars expr)
366   = dsExpr expr `thenDs` \ core_expr ->
367     returnDs (mkLams tyvars core_expr)
368
369 dsExpr (TyApp expr tys)
370   = dsExpr expr         `thenDs` \ core_expr ->
371     returnDs (mkTyApps core_expr tys)
372 \end{code}
373
374
375 Various data construction things
376 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
377 \begin{code}
378 dsExpr (ExplicitListOut ty xs)
379   = go xs
380   where
381     list_ty   = mkListTy ty
382
383     go []     = returnDs (mkNilExpr ty)
384     go (x:xs) = dsExpr x                                `thenDs` \ core_x ->
385                 go xs                                   `thenDs` \ core_xs ->
386                 returnDs (mkConApp consDataCon [Type ty, core_x, core_xs])
387
388 dsExpr (ExplicitTuple expr_list boxed)
389   = mapDs dsExpr expr_list        `thenDs` \ core_exprs  ->
390     returnDs (mkConApp ((if boxed 
391                             then tupleCon 
392                             else unboxedTupleCon) (length expr_list))
393                 (map (Type . coreExprType) core_exprs ++ core_exprs))
394
395 dsExpr (HsCon con_id [ty] [arg])
396   | isNewTyCon tycon
397   = dsExpr arg               `thenDs` \ arg' ->
398     returnDs (Note (Coerce result_ty (coreExprType arg')) arg')
399   where
400     result_ty = mkTyConApp tycon [ty]
401     tycon     = dataConTyCon con_id
402
403 dsExpr (HsCon con_id tys args)
404   = mapDs dsExpr args             `thenDs` \ args2  ->
405     returnDs (mkConApp con_id (map Type tys ++ args2))
406
407 dsExpr (ArithSeqOut expr (From from))
408   = dsExpr expr           `thenDs` \ expr2 ->
409     dsExpr from           `thenDs` \ from2 ->
410     returnDs (App expr2 from2)
411
412 dsExpr (ArithSeqOut expr (FromTo from two))
413   = dsExpr expr           `thenDs` \ expr2 ->
414     dsExpr from           `thenDs` \ from2 ->
415     dsExpr two            `thenDs` \ two2 ->
416     returnDs (mkApps expr2 [from2, two2])
417
418 dsExpr (ArithSeqOut expr (FromThen from thn))
419   = dsExpr expr           `thenDs` \ expr2 ->
420     dsExpr from           `thenDs` \ from2 ->
421     dsExpr thn            `thenDs` \ thn2 ->
422     returnDs (mkApps expr2 [from2, thn2])
423
424 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
425   = dsExpr expr           `thenDs` \ expr2 ->
426     dsExpr from           `thenDs` \ from2 ->
427     dsExpr thn            `thenDs` \ thn2 ->
428     dsExpr two            `thenDs` \ two2 ->
429     returnDs (mkApps expr2 [from2, thn2, two2])
430 \end{code}
431
432 Record construction and update
433 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
434 For record construction we do this (assuming T has three arguments)
435
436         T { op2 = e }
437 ==>
438         let err = /\a -> recConErr a 
439         T (recConErr t1 "M.lhs/230/op1") 
440           e 
441           (recConErr t1 "M.lhs/230/op3")
442
443 recConErr then converts its arugment string into a proper message
444 before printing it as
445
446         M.lhs, line 230: missing field op1 was evaluated
447
448
449 \begin{code}
450 dsExpr (RecordConOut data_con con_expr rbinds)
451   = dsExpr con_expr     `thenDs` \ con_expr' ->
452     let
453         (arg_tys, _) = splitFunTys (coreExprType con_expr')
454
455         mk_arg (arg_ty, lbl)
456           = case [rhs | (sel_id,rhs,_) <- rbinds,
457                         lbl == recordSelectorFieldLabel sel_id] of
458               (rhs:rhss) -> ASSERT( null rhss )
459                             dsExpr rhs
460               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
461     in
462     mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys (dataConFieldLabels data_con)) `thenDs` \ con_args ->
463     returnDs (mkApps con_expr' con_args)
464 \end{code}
465
466 Record update is a little harder. Suppose we have the decl:
467
468         data T = T1 {op1, op2, op3 :: Int}
469                | T2 {op4, op2 :: Int}
470                | T3
471
472 Then we translate as follows:
473
474         r { op2 = e }
475 ===>
476         let op2 = e in
477         case r of
478           T1 op1 _ op3 -> T1 op1 op2 op3
479           T2 op4 _     -> T2 op4 op2
480           other        -> recUpdError "M.lhs/230"
481
482 It's important that we use the constructor Ids for T1, T2 etc on the
483 RHSs, and do not generate a Core Con directly, because the constructor
484 might do some argument-evaluation first; and may have to throw away some
485 dictionaries.
486
487 \begin{code}
488 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
489   = dsExpr record_expr          `thenDs` \ record_expr' ->
490
491         -- Desugar the rbinds, and generate let-bindings if
492         -- necessary so that we don't lose sharing
493
494     let
495         ds_rbind (sel_id, rhs, pun_flag)
496           = dsExpr rhs                          `thenDs` \ rhs' ->
497             returnDs (recordSelectorFieldLabel sel_id, rhs')
498     in
499     mapDs ds_rbind rbinds                       `thenDs` \ rbinds' ->
500     let
501         record_in_ty               = coreExprType record_expr'
502         (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
503         (_,     out_inst_tys, _)   = splitAlgTyConApp record_out_ty
504         cons_to_upd                = filter has_all_fields cons
505
506         -- initial_args are passed to every constructor
507         initial_args            = map Type out_inst_tys ++ map Var dicts
508                 
509         mk_val_arg field old_arg_id 
510           = case [rhs | (f, rhs) <- rbinds', field == f] of
511               (rhs:rest) -> ASSERT(null rest) rhs
512               []         -> Var old_arg_id
513
514         mk_alt con
515           = newSysLocalsDs (dataConArgTys con in_inst_tys)      `thenDs` \ arg_ids ->
516             let 
517                 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
518                                         (dataConFieldLabels con) arg_ids
519                 rhs = mkApps (mkApps (Var (dataConId con)) initial_args) val_args
520             in
521             returnDs (DataCon con, arg_ids, rhs)
522
523         mk_default
524           | length cons_to_upd == length cons 
525           = returnDs []
526           | otherwise                       
527           = mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty ""      `thenDs` \ err ->
528             returnDs [(DEFAULT, [], err)]
529     in
530         -- Record stuff doesn't work for existentials
531     ASSERT( all (not . isExistentialDataCon) cons )
532
533     newSysLocalDs record_in_ty  `thenDs` \ case_bndr ->
534     mapDs mk_alt cons_to_upd    `thenDs` \ alts ->
535     mk_default                  `thenDs` \ deflt ->
536
537     returnDs (Case record_expr' case_bndr (alts ++ deflt))
538   where
539     has_all_fields :: DataCon -> Bool
540     has_all_fields con_id 
541       = all ok rbinds
542       where
543         con_fields        = dataConFieldLabels con_id
544         ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
545 \end{code}
546
547 Dictionary lambda and application
548 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
549 @DictLam@ and @DictApp@ turn into the regular old things.
550 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
551 complicated; reminiscent of fully-applied constructors.
552 \begin{code}
553 dsExpr (DictLam dictvars expr)
554   = dsExpr expr `thenDs` \ core_expr ->
555     returnDs (mkLams dictvars core_expr)
556
557 ------------------
558
559 dsExpr (DictApp expr dicts)     -- becomes a curried application
560   = dsExpr expr                 `thenDs` \ core_expr ->
561     returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
562 \end{code}
563
564 \begin{code}
565
566
567 #ifdef DEBUG
568 -- HsSyn constructs that just shouldn't be here:
569 dsExpr (HsDo _ _ _)         = panic "dsExpr:HsDo"
570 dsExpr (ExplicitList _)     = panic "dsExpr:ExplicitList"
571 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
572 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
573 #endif
574
575 out_of_range_msg                           -- ditto
576   = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
577 \end{code}
578
579 %--------------------------------------------------------------------
580
581 Basically does the translation given in the Haskell~1.3 report:
582
583 \begin{code}
584 dsDo    :: StmtCtxt
585         -> [TypecheckedStmt]
586         -> Id           -- id for: return m
587         -> Id           -- id for: (>>=) m
588         -> Id           -- id for: zero m
589         -> Type         -- Element type; the whole expression has type (m t)
590         -> DsM CoreExpr
591
592 dsDo do_or_lc stmts return_id then_id zero_id result_ty
593   = let
594         (_, b_ty) = splitAppTy result_ty        -- result_ty must be of the form (m b)
595         
596         go [ReturnStmt expr] 
597           = dsExpr expr                 `thenDs` \ expr2 ->
598             returnDs (mkApps (Var return_id) [Type b_ty, expr2])
599     
600         go (GuardStmt expr locn : stmts)
601           = do_expr expr locn                   `thenDs` \ expr2 ->
602             go stmts                            `thenDs` \ rest ->
603             returnDs (mkIfThenElse expr2 rest (App (Var zero_id) (Type b_ty)))
604     
605         go (ExprStmt expr locn : stmts)
606           = do_expr expr locn           `thenDs` \ expr2 ->
607             let
608                 (_, a_ty) = splitAppTy (coreExprType expr2)     -- Must be of form (m a)
609             in
610             if null stmts then
611                 returnDs expr2
612             else
613                 go stmts                `thenDs` \ rest  ->
614                 newSysLocalDs a_ty              `thenDs` \ ignored_result_id ->
615                 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2, 
616                                                 Lam ignored_result_id rest])
617     
618         go (LetStmt binds : stmts )
619           = go stmts            `thenDs` \ rest   ->
620             dsLet binds rest
621             
622         go (BindStmt pat expr locn : stmts)
623           = putSrcLocDs locn $
624             dsExpr expr            `thenDs` \ expr2 ->
625             let
626                 (_, a_ty)  = splitAppTy (coreExprType expr2)    -- Must be of form (m a)
627                 zero_expr  = TyApp (HsVar zero_id) [b_ty]
628                 main_match = mkSimpleMatch [pat] (HsDoOut do_or_lc stmts return_id then_id zero_id result_ty locn)
629                                            (Just result_ty) locn
630                 the_matches
631                   = if failureFreePat pat
632                     then [main_match]
633                     else [main_match, mkSimpleMatch [WildPat a_ty] zero_expr (Just result_ty) locn]
634             in
635             matchWrapper DoBindMatch the_matches match_msg
636                                 `thenDs` \ (binders, matching_code) ->
637             returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
638                                             mkLams binders matching_code])
639     in
640     go stmts
641
642   where
643     do_expr expr locn = putSrcLocDs locn (dsExpr expr)
644
645     match_msg = case do_or_lc of
646                         DoStmt   -> "`do' statement"
647                         ListComp -> "comprehension"
648 \end{code}
649
650 \begin{code}
651 var_pat (WildPat _) = True
652 var_pat (VarPat _) = True
653 var_pat _ = False
654 \end{code}
655