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