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