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