[project @ 1998-12-02 13:17:09 by simonm]
[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                         )
16 import TcHsSyn          ( TypecheckedHsExpr, TypecheckedHsBinds,
17                           TypecheckedStmt,
18                           maybeBoxedPrimType
19
20                         )
21 import CoreSyn
22
23 import DsMonad
24 import DsBinds          ( dsMonoBinds )
25 import DsGRHSs          ( dsGuarded )
26 import DsCCall          ( dsCCall )
27 import DsListComp       ( dsListComp )
28 import DsUtils          ( mkErrorAppDs )
29 import Match            ( matchWrapper, matchSimply )
30
31 import CoreUtils        ( coreExprType )
32 import CostCentre       ( mkUserCC )
33 import FieldLabel       ( FieldLabel )
34 import Id               ( Id, idType, recordSelectorFieldLabel )
35 import Const            ( Con(..) )
36 import DataCon          ( DataCon, dataConId, dataConTyCon, dataConArgTys, dataConFieldLabels )
37 import Const            ( mkMachInt, Literal(..) )
38 import PrelVals         ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID )
39 import TyCon            ( isNewTyCon )
40 import DataCon          ( isExistentialDataCon )
41 import Type             ( splitFunTys, mkTyConApp,
42                           splitAlgTyConApp, splitTyConApp_maybe,
43                           splitAppTy, isUnLiftedType, Type
44                         )
45 import TysWiredIn       ( tupleCon, unboxedTupleCon,
46                           consDataCon, listTyCon, mkListTy,
47                           charDataCon, charTy, stringTy
48                         )
49 import BasicTypes       ( RecFlag(..) )
50 import Maybes           ( maybeToBool )
51 import Util             ( zipEqual, zipWithEqual )
52 import Outputable
53 \end{code}
54
55
56 %************************************************************************
57 %*                                                                      *
58 \subsection{dsLet}
59 %*                                                                      *
60 %************************************************************************
61
62 @dsLet@ is a match-result transformer, taking the MatchResult for the body
63 and transforming it into one for the let-bindings enclosing the body.
64
65 This may seem a bit odd, but (source) let bindings can contain unboxed
66 binds like
67
68         C x# = e
69
70 This must be transformed to a case expression and, if the type has
71 more than one constructor, may fail.
72
73 \begin{code}
74 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
75
76 dsLet EmptyBinds body
77   = returnDs body
78
79 dsLet (ThenBinds b1 b2) body
80   = dsLet b2 body       `thenDs` \ body' ->
81     dsLet b1 body'
82   
83 -- Special case for bindings which bind unlifted variables
84 dsLet (MonoBind (AbsBinds [] [] binder_triples bind) sigs is_rec) body
85   | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
86   = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
87     putSrcLocDs loc                                                     $
88     dsGuarded grhss                                                     `thenDs` \ rhs ->
89     let
90         body' = foldr bind body binder_triples
91         bind (tyvars, g, l) body = ASSERT( null tyvars )
92                                    bindNonRec g (Var l) body
93     in
94     mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat))    `thenDs` \ error_expr ->
95     matchSimply rhs PatBindMatch pat body' error_expr
96   where
97     PatMonoBind pat grhss loc = bind
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@[PatMatch (TuplePat ps boxed) (GRHSMatch rhs)]
312                 src_loc)
313  | all var_pat ps 
314  =  putSrcLocDs src_loc $
315     dsExpr discrim                              `thenDs` \ core_discrim ->
316     matchWrapper CaseMatch matches "case"       `thenDs` \ ([discrim_var], matching_code) ->
317     case matching_code of
318         Case (Var x) bndr alts | x == discrim_var -> 
319                 returnDs (Case core_discrim bndr alts)
320         _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
321
322 dsExpr (HsCase discrim matches src_loc)
323   = putSrcLocDs src_loc $
324     dsExpr discrim                              `thenDs` \ core_discrim ->
325     matchWrapper CaseMatch matches "case"       `thenDs` \ ([discrim_var], matching_code) ->
326     returnDs (bindNonRec discrim_var core_discrim matching_code)
327
328 dsExpr (HsLet binds body)
329   = dsExpr body         `thenDs` \ body' ->
330     dsLet binds body'
331     
332 dsExpr (HsDoOut do_or_lc stmts return_id then_id zero_id result_ty src_loc)
333   | maybeToBool maybe_list_comp
334   =     -- Special case for list comprehensions
335     putSrcLocDs src_loc $
336     dsListComp stmts elt_ty
337
338   | otherwise
339   = putSrcLocDs src_loc $
340     dsDo do_or_lc stmts return_id then_id zero_id result_ty
341   where
342     maybe_list_comp 
343         = case (do_or_lc, splitTyConApp_maybe result_ty) of
344             (ListComp, Just (tycon, [elt_ty]))
345                   | tycon == listTyCon
346                  -> Just elt_ty
347             other -> Nothing
348         -- We need the ListComp form to use deListComp (rather than the "do" form)
349         -- because the "return" in a do block is a call to "PrelBase.return", and
350         -- not a ReturnStmt.  Only the ListComp form has ReturnStmts
351
352     Just elt_ty = maybe_list_comp
353
354 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
355   = putSrcLocDs src_loc $
356     dsExpr guard_expr   `thenDs` \ core_guard ->
357     dsExpr then_expr    `thenDs` \ core_then ->
358     dsExpr else_expr    `thenDs` \ core_else ->
359     returnDs (mkIfThenElse core_guard core_then core_else)
360 \end{code}
361
362
363 Type lambda and application
364 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
365 \begin{code}
366 dsExpr (TyLam tyvars expr)
367   = dsExpr expr `thenDs` \ core_expr ->
368     returnDs (mkLams tyvars core_expr)
369
370 dsExpr (TyApp expr tys)
371   = dsExpr expr         `thenDs` \ core_expr ->
372     returnDs (mkTyApps core_expr tys)
373 \end{code}
374
375
376 Various data construction things
377 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
378 \begin{code}
379 dsExpr (ExplicitListOut ty xs)
380   = go xs
381   where
382     list_ty   = mkListTy ty
383
384     go []     = returnDs (mkNilExpr ty)
385     go (x:xs) = dsExpr x                                `thenDs` \ core_x ->
386                 go xs                                   `thenDs` \ core_xs ->
387                 returnDs (mkConApp consDataCon [Type ty, core_x, core_xs])
388
389 dsExpr (ExplicitTuple expr_list boxed)
390   = mapDs dsExpr expr_list        `thenDs` \ core_exprs  ->
391     returnDs (mkConApp ((if boxed 
392                             then tupleCon 
393                             else unboxedTupleCon) (length expr_list))
394                 (map (Type . coreExprType) core_exprs ++ core_exprs))
395
396 dsExpr (HsCon con_id [ty] [arg])
397   | isNewTyCon tycon
398   = dsExpr arg               `thenDs` \ arg' ->
399     returnDs (Note (Coerce result_ty (coreExprType arg')) arg')
400   where
401     result_ty = mkTyConApp tycon [ty]
402     tycon     = dataConTyCon con_id
403
404 dsExpr (HsCon con_id tys args)
405   = mapDs dsExpr args             `thenDs` \ args2  ->
406     returnDs (mkConApp con_id (map Type tys ++ args2))
407
408 dsExpr (ArithSeqOut expr (From from))
409   = dsExpr expr           `thenDs` \ expr2 ->
410     dsExpr from           `thenDs` \ from2 ->
411     returnDs (App expr2 from2)
412
413 dsExpr (ArithSeqOut expr (FromTo from two))
414   = dsExpr expr           `thenDs` \ expr2 ->
415     dsExpr from           `thenDs` \ from2 ->
416     dsExpr two            `thenDs` \ two2 ->
417     returnDs (mkApps expr2 [from2, two2])
418
419 dsExpr (ArithSeqOut expr (FromThen from thn))
420   = dsExpr expr           `thenDs` \ expr2 ->
421     dsExpr from           `thenDs` \ from2 ->
422     dsExpr thn            `thenDs` \ thn2 ->
423     returnDs (mkApps expr2 [from2, thn2])
424
425 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
426   = dsExpr expr           `thenDs` \ expr2 ->
427     dsExpr from           `thenDs` \ from2 ->
428     dsExpr thn            `thenDs` \ thn2 ->
429     dsExpr two            `thenDs` \ two2 ->
430     returnDs (mkApps expr2 [from2, thn2, two2])
431 \end{code}
432
433 Record construction and update
434 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
435 For record construction we do this (assuming T has three arguments)
436
437         T { op2 = e }
438 ==>
439         let err = /\a -> recConErr a 
440         T (recConErr t1 "M.lhs/230/op1") 
441           e 
442           (recConErr t1 "M.lhs/230/op3")
443
444 recConErr then converts its arugment string into a proper message
445 before printing it as
446
447         M.lhs, line 230: missing field op1 was evaluated
448
449
450 \begin{code}
451 dsExpr (RecordConOut data_con con_expr rbinds)
452   = dsExpr con_expr     `thenDs` \ con_expr' ->
453     let
454         (arg_tys, _) = splitFunTys (coreExprType con_expr')
455
456         mk_arg (arg_ty, lbl)
457           = case [rhs | (sel_id,rhs,_) <- rbinds,
458                         lbl == recordSelectorFieldLabel sel_id] of
459               (rhs:rhss) -> ASSERT( null rhss )
460                             dsExpr rhs
461               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
462     in
463     mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys (dataConFieldLabels data_con)) `thenDs` \ con_args ->
464     returnDs (mkApps con_expr' con_args)
465 \end{code}
466
467 Record update is a little harder. Suppose we have the decl:
468
469         data T = T1 {op1, op2, op3 :: Int}
470                | T2 {op4, op2 :: Int}
471                | T3
472
473 Then we translate as follows:
474
475         r { op2 = e }
476 ===>
477         let op2 = e in
478         case r of
479           T1 op1 _ op3 -> T1 op1 op2 op3
480           T2 op4 _     -> T2 op4 op2
481           other        -> recUpdError "M.lhs/230"
482
483 It's important that we use the constructor Ids for T1, T2 etc on the
484 RHSs, and do not generate a Core Con directly, because the constructor
485 might do some argument-evaluation first; and may have to throw away some
486 dictionaries.
487
488 \begin{code}
489 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
490   = dsExpr record_expr          `thenDs` \ record_expr' ->
491
492         -- Desugar the rbinds, and generate let-bindings if
493         -- necessary so that we don't lose sharing
494
495     let
496         ds_rbind (sel_id, rhs, pun_flag)
497           = dsExpr rhs                          `thenDs` \ rhs' ->
498             returnDs (recordSelectorFieldLabel sel_id, rhs')
499     in
500     mapDs ds_rbind rbinds                       `thenDs` \ rbinds' ->
501     let
502         record_in_ty               = coreExprType record_expr'
503         (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
504         (_,     out_inst_tys, _)   = splitAlgTyConApp record_out_ty
505         cons_to_upd                = filter has_all_fields cons
506
507         -- initial_args are passed to every constructor
508         initial_args            = map Type out_inst_tys ++ map Var dicts
509                 
510         mk_val_arg field old_arg_id 
511           = case [rhs | (f, rhs) <- rbinds', field == f] of
512               (rhs:rest) -> ASSERT(null rest) rhs
513               []         -> Var old_arg_id
514
515         mk_alt con
516           = newSysLocalsDs (dataConArgTys con in_inst_tys)      `thenDs` \ arg_ids ->
517             let 
518                 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
519                                         (dataConFieldLabels con) arg_ids
520                 rhs = mkApps (mkApps (Var (dataConId con)) initial_args) val_args
521             in
522             returnDs (DataCon con, arg_ids, rhs)
523
524         mk_default
525           | length cons_to_upd == length cons 
526           = returnDs []
527           | otherwise                       
528           = mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty ""      `thenDs` \ err ->
529             returnDs [(DEFAULT, [], err)]
530     in
531         -- Record stuff doesn't work for existentials
532     ASSERT( all (not . isExistentialDataCon) cons )
533
534     newSysLocalDs record_in_ty  `thenDs` \ case_bndr ->
535     mapDs mk_alt cons_to_upd    `thenDs` \ alts ->
536     mk_default                  `thenDs` \ deflt ->
537
538     returnDs (Case record_expr' case_bndr (alts ++ deflt))
539   where
540     has_all_fields :: DataCon -> Bool
541     has_all_fields con_id 
542       = all ok rbinds
543       where
544         con_fields        = dataConFieldLabels con_id
545         ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
546 \end{code}
547
548 Dictionary lambda and application
549 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
550 @DictLam@ and @DictApp@ turn into the regular old things.
551 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
552 complicated; reminiscent of fully-applied constructors.
553 \begin{code}
554 dsExpr (DictLam dictvars expr)
555   = dsExpr expr `thenDs` \ core_expr ->
556     returnDs (mkLams dictvars core_expr)
557
558 ------------------
559
560 dsExpr (DictApp expr dicts)     -- becomes a curried application
561   = dsExpr expr                 `thenDs` \ core_expr ->
562     returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
563 \end{code}
564
565 \begin{code}
566
567
568 #ifdef DEBUG
569 -- HsSyn constructs that just shouldn't be here:
570 dsExpr (HsDo _ _ _)         = panic "dsExpr:HsDo"
571 dsExpr (ExplicitList _)     = panic "dsExpr:ExplicitList"
572 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
573 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
574 #endif
575
576 out_of_range_msg                           -- ditto
577   = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
578 \end{code}
579
580 %--------------------------------------------------------------------
581
582 Basically does the translation given in the Haskell~1.3 report:
583
584 \begin{code}
585 dsDo    :: StmtCtxt
586         -> [TypecheckedStmt]
587         -> Id           -- id for: return m
588         -> Id           -- id for: (>>=) m
589         -> Id           -- id for: zero m
590         -> Type         -- Element type; the whole expression has type (m t)
591         -> DsM CoreExpr
592
593 dsDo do_or_lc stmts return_id then_id zero_id result_ty
594   = let
595         (_, b_ty) = splitAppTy result_ty        -- result_ty must be of the form (m b)
596         
597         go [ReturnStmt expr] 
598           = dsExpr expr                 `thenDs` \ expr2 ->
599             returnDs (mkApps (Var return_id) [Type b_ty, expr2])
600     
601         go (GuardStmt expr locn : stmts)
602           = do_expr expr locn                   `thenDs` \ expr2 ->
603             go stmts                            `thenDs` \ rest ->
604             returnDs (mkIfThenElse expr2 rest (App (Var zero_id) (Type b_ty)))
605     
606         go (ExprStmt expr locn : stmts)
607           = do_expr expr locn           `thenDs` \ expr2 ->
608             let
609                 (_, a_ty) = splitAppTy (coreExprType expr2)     -- Must be of form (m a)
610             in
611             if null stmts then
612                 returnDs expr2
613             else
614                 go stmts                `thenDs` \ rest  ->
615                 newSysLocalDs a_ty              `thenDs` \ ignored_result_id ->
616                 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2, 
617                                                 Lam ignored_result_id rest])
618     
619         go (LetStmt binds : stmts )
620           = go stmts            `thenDs` \ rest   ->
621             dsLet binds rest
622             
623         go (BindStmt pat expr locn : stmts)
624           = putSrcLocDs locn $
625             dsExpr expr            `thenDs` \ expr2 ->
626             let
627                 (_, a_ty)  = splitAppTy (coreExprType expr2)    -- Must be of form (m a)
628                 zero_expr  = TyApp (HsVar zero_id) [b_ty]
629                 main_match = PatMatch pat (SimpleMatch (
630                              HsDoOut do_or_lc stmts return_id then_id zero_id result_ty locn))
631                 the_matches
632                   = if failureFreePat pat
633                     then [main_match]
634                     else [main_match, PatMatch (WildPat a_ty) (SimpleMatch zero_expr)]
635             in
636             matchWrapper DoBindMatch the_matches match_msg
637                                 `thenDs` \ (binders, matching_code) ->
638             returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
639                                             mkLams binders matching_code])
640     in
641     go stmts
642
643   where
644     do_expr expr locn = putSrcLocDs locn (dsExpr expr)
645
646     match_msg = case do_or_lc of
647                         DoStmt   -> "`do' statement"
648                         ListComp -> "comprehension"
649 \end{code}
650
651 \begin{code}
652 var_pat (WildPat _) = True
653 var_pat (VarPat _) = True
654 var_pat _ = False
655 \end{code}
656