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