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