[project @ 1999-03-29 11:33:29 by sof]
[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   | isUnLiftedType ty
188   = returnDs (mkLit (MachLitLit str ty))
189   | otherwise
190   = case (maybeBoxedPrimType ty) of
191       Just (boxing_data_con, prim_ty) ->
192             returnDs ( mkConApp boxing_data_con [mkLit (MachLitLit str prim_ty)] )
193       _ -> 
194         pprError "ERROR:"
195                  (vcat
196                    [ hcat [ text "Cannot see data constructor of ``literal-literal''s type: "
197                          , text "value:", quotes (quotes (ptext str))
198                          , text "; type: ", ppr ty
199                          ]
200                    , text "Try compiling with -fno-prune-tydecls."
201                    ])
202                   
203   where
204     (data_con, prim_ty)
205       = case (maybeBoxedPrimType ty) of
206           Just (boxing_data_con, prim_ty) -> (boxing_data_con, prim_ty)
207           Nothing
208             -> pprPanic "ERROR: ``literal-literal'' not a single-constructor type: "
209                         (hcat [ptext str, text "; type: ", ppr ty])
210
211 dsExpr (HsLitOut (HsInt i) ty)
212   = returnDs (mkLit (NoRepInteger i ty))
213
214 dsExpr (HsLitOut (HsFrac r) ty)
215   = returnDs (mkLit (NoRepRational r ty))
216
217 -- others where we know what to do:
218
219 dsExpr (HsLitOut (HsIntPrim i) _)
220   | (i >= toInteger minInt && i <= toInteger maxInt) 
221   = returnDs (mkLit (mkMachInt i))
222   | otherwise
223   = error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
224
225 dsExpr (HsLitOut (HsFloatPrim f) _)
226   = returnDs (mkLit (MachFloat f))
227     -- ToDo: range checking needed!
228
229 dsExpr (HsLitOut (HsDoublePrim d) _)
230   = returnDs (mkLit (MachDouble d))
231     -- ToDo: range checking needed!
232
233 dsExpr (HsLitOut (HsChar c) _)
234   = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
235
236 dsExpr (HsLitOut (HsCharPrim c) _)
237   = returnDs (mkLit (MachChar c))
238
239 dsExpr (HsLitOut (HsStringPrim s) _)
240   = returnDs (mkLit (MachStr s))
241
242 -- end of literals magic. --
243
244 dsExpr expr@(HsLam a_Match)
245   = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
246     returnDs (mkLams binders matching_code)
247
248 dsExpr expr@(HsApp fun arg)      
249   = dsExpr fun          `thenDs` \ core_fun ->
250     dsExpr arg          `thenDs` \ core_arg ->
251     returnDs (core_fun `App` core_arg)
252
253 \end{code}
254
255 Operator sections.  At first it looks as if we can convert
256 \begin{verbatim}
257         (expr op)
258 \end{verbatim}
259 to
260 \begin{verbatim}
261         \x -> op expr x
262 \end{verbatim}
263
264 But no!  expr might be a redex, and we can lose laziness badly this
265 way.  Consider
266 \begin{verbatim}
267         map (expr op) xs
268 \end{verbatim}
269 for example.  So we convert instead to
270 \begin{verbatim}
271         let y = expr in \x -> op y x
272 \end{verbatim}
273 If \tr{expr} is actually just a variable, say, then the simplifier
274 will sort it out.
275
276 \begin{code}
277 dsExpr (OpApp e1 op _ e2)
278   = dsExpr op                                           `thenDs` \ core_op ->
279     -- for the type of y, we need the type of op's 2nd argument
280     let
281         (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
282     in
283     dsExpr e1                           `thenDs` \ x_core ->
284     dsExpr e2                           `thenDs` \ y_core ->
285     returnDs (mkApps core_op [x_core, y_core])
286     
287 dsExpr (SectionL expr op)
288   = dsExpr op                                           `thenDs` \ core_op ->
289     -- for the type of y, we need the type of op's 2nd argument
290     let
291         (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
292     in
293     dsExpr expr                         `thenDs` \ x_core ->
294     newSysLocalDs x_ty                  `thenDs` \ x_id ->
295     newSysLocalDs y_ty                  `thenDs` \ y_id ->
296
297     returnDs (bindNonRec x_id x_core $
298               Lam y_id (mkApps core_op [Var x_id, Var y_id]))
299
300 -- dsExpr (SectionR op expr)    -- \ x -> op x expr
301 dsExpr (SectionR op expr)
302   = dsExpr op                   `thenDs` \ core_op ->
303     -- for the type of x, we need the type of op's 2nd argument
304     let
305         (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
306     in
307     dsExpr expr                         `thenDs` \ y_core ->
308     newSysLocalDs x_ty                  `thenDs` \ x_id ->
309     newSysLocalDs y_ty                  `thenDs` \ y_id ->
310
311     returnDs (bindNonRec y_id y_core $
312               Lam x_id (mkApps core_op [Var x_id, Var y_id]))
313
314 dsExpr (CCall label args may_gc is_asm result_ty)
315   = mapDs dsExpr args           `thenDs` \ core_args ->
316     dsCCall label core_args may_gc is_asm result_ty
317         -- dsCCall does all the unboxification, etc.
318
319 dsExpr (HsSCC cc expr)
320   = dsExpr expr                 `thenDs` \ core_expr ->
321     getModuleAndGroupDs         `thenDs` \ (mod_name, group_name) ->
322     returnDs (Note (SCC (mkUserCC cc mod_name group_name)) core_expr)
323
324 -- special case to handle unboxed tuple patterns.
325
326 dsExpr (HsCase discrim matches@[Match _ [TuplePat ps boxed] _ _] src_loc)
327  | not boxed && all var_pat ps 
328  =  putSrcLocDs src_loc $
329     dsExpr discrim                              `thenDs` \ core_discrim ->
330     matchWrapper CaseMatch matches "case"       `thenDs` \ ([discrim_var], matching_code) ->
331     case matching_code of
332         Case (Var x) bndr alts | x == discrim_var -> 
333                 returnDs (Case core_discrim bndr alts)
334         _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
335
336 dsExpr (HsCase discrim matches src_loc)
337   = putSrcLocDs src_loc $
338     dsExpr discrim                              `thenDs` \ core_discrim ->
339     matchWrapper CaseMatch matches "case"       `thenDs` \ ([discrim_var], matching_code) ->
340     returnDs (bindNonRec discrim_var core_discrim matching_code)
341
342 dsExpr (HsLet binds body)
343   = dsExpr body         `thenDs` \ body' ->
344     dsLet binds body'
345     
346 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
347   | maybeToBool maybe_list_comp
348   =     -- Special case for list comprehensions
349     putSrcLocDs src_loc $
350     dsListComp stmts elt_ty
351
352   | otherwise
353   = putSrcLocDs src_loc $
354     dsDo do_or_lc stmts return_id then_id fail_id result_ty
355   where
356     maybe_list_comp 
357         = case (do_or_lc, splitTyConApp_maybe result_ty) of
358             (ListComp, Just (tycon, [elt_ty]))
359                   | tycon == listTyCon
360                  -> Just elt_ty
361             other -> Nothing
362         -- We need the ListComp form to use deListComp (rather than the "do" form)
363         -- because the "return" in a do block is a call to "PrelBase.return", and
364         -- not a ReturnStmt.  Only the ListComp form has ReturnStmts
365
366     Just elt_ty = maybe_list_comp
367
368 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
369   = putSrcLocDs src_loc $
370     dsExpr guard_expr   `thenDs` \ core_guard ->
371     dsExpr then_expr    `thenDs` \ core_then ->
372     dsExpr else_expr    `thenDs` \ core_else ->
373     returnDs (mkIfThenElse core_guard core_then core_else)
374 \end{code}
375
376
377 Type lambda and application
378 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
379 \begin{code}
380 dsExpr (TyLam tyvars expr)
381   = dsExpr expr `thenDs` \ core_expr ->
382     returnDs (mkLams tyvars core_expr)
383
384 dsExpr (TyApp expr tys)
385   = dsExpr expr         `thenDs` \ core_expr ->
386     returnDs (mkTyApps core_expr tys)
387 \end{code}
388
389
390 Various data construction things
391 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
392 \begin{code}
393 dsExpr (ExplicitListOut ty xs)
394   = go xs
395   where
396     list_ty   = mkListTy ty
397
398     go []     = returnDs (mkNilExpr ty)
399     go (x:xs) = dsExpr x                                `thenDs` \ core_x ->
400                 go xs                                   `thenDs` \ core_xs ->
401                 returnDs (mkConApp consDataCon [Type ty, core_x, core_xs])
402
403 dsExpr (ExplicitTuple expr_list boxed)
404   = mapDs dsExpr expr_list        `thenDs` \ core_exprs  ->
405     returnDs (mkConApp ((if boxed 
406                             then tupleCon 
407                             else unboxedTupleCon) (length expr_list))
408                 (map (Type . coreExprType) core_exprs ++ core_exprs))
409
410 dsExpr (HsCon con_id [ty] [arg])
411   | isNewTyCon tycon
412   = dsExpr arg               `thenDs` \ arg' ->
413     returnDs (Note (Coerce result_ty (coreExprType arg')) arg')
414   where
415     result_ty = mkTyConApp tycon [ty]
416     tycon     = dataConTyCon con_id
417
418 dsExpr (HsCon con_id tys args)
419   = mapDs dsExpr args             `thenDs` \ args2  ->
420     returnDs (mkConApp con_id (map Type tys ++ args2))
421
422 dsExpr (ArithSeqOut expr (From from))
423   = dsExpr expr           `thenDs` \ expr2 ->
424     dsExpr from           `thenDs` \ from2 ->
425     returnDs (App expr2 from2)
426
427 dsExpr (ArithSeqOut expr (FromTo from two))
428   = dsExpr expr           `thenDs` \ expr2 ->
429     dsExpr from           `thenDs` \ from2 ->
430     dsExpr two            `thenDs` \ two2 ->
431     returnDs (mkApps expr2 [from2, two2])
432
433 dsExpr (ArithSeqOut expr (FromThen from thn))
434   = dsExpr expr           `thenDs` \ expr2 ->
435     dsExpr from           `thenDs` \ from2 ->
436     dsExpr thn            `thenDs` \ thn2 ->
437     returnDs (mkApps expr2 [from2, thn2])
438
439 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
440   = dsExpr expr           `thenDs` \ expr2 ->
441     dsExpr from           `thenDs` \ from2 ->
442     dsExpr thn            `thenDs` \ thn2 ->
443     dsExpr two            `thenDs` \ two2 ->
444     returnDs (mkApps expr2 [from2, thn2, two2])
445 \end{code}
446
447 Record construction and update
448 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
449 For record construction we do this (assuming T has three arguments)
450
451         T { op2 = e }
452 ==>
453         let err = /\a -> recConErr a 
454         T (recConErr t1 "M.lhs/230/op1") 
455           e 
456           (recConErr t1 "M.lhs/230/op3")
457
458 recConErr then converts its arugment string into a proper message
459 before printing it as
460
461         M.lhs, line 230: missing field op1 was evaluated
462
463
464 \begin{code}
465 dsExpr (RecordConOut data_con con_expr rbinds)
466   = dsExpr con_expr     `thenDs` \ con_expr' ->
467     let
468         (arg_tys, _) = splitFunTys (coreExprType con_expr')
469
470         mk_arg (arg_ty, lbl)
471           = case [rhs | (sel_id,rhs,_) <- rbinds,
472                         lbl == recordSelectorFieldLabel sel_id] of
473               (rhs:rhss) -> ASSERT( null rhss )
474                             dsExpr rhs
475               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
476     in
477     mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys (dataConFieldLabels data_con)) `thenDs` \ con_args ->
478     returnDs (mkApps con_expr' con_args)
479 \end{code}
480
481 Record update is a little harder. Suppose we have the decl:
482
483         data T = T1 {op1, op2, op3 :: Int}
484                | T2 {op4, op2 :: Int}
485                | T3
486
487 Then we translate as follows:
488
489         r { op2 = e }
490 ===>
491         let op2 = e in
492         case r of
493           T1 op1 _ op3 -> T1 op1 op2 op3
494           T2 op4 _     -> T2 op4 op2
495           other        -> recUpdError "M.lhs/230"
496
497 It's important that we use the constructor Ids for T1, T2 etc on the
498 RHSs, and do not generate a Core Con directly, because the constructor
499 might do some argument-evaluation first; and may have to throw away some
500 dictionaries.
501
502 \begin{code}
503 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
504   = dsExpr record_expr          `thenDs` \ record_expr' ->
505
506         -- Desugar the rbinds, and generate let-bindings if
507         -- necessary so that we don't lose sharing
508
509     let
510         ds_rbind (sel_id, rhs, pun_flag)
511           = dsExpr rhs                          `thenDs` \ rhs' ->
512             returnDs (recordSelectorFieldLabel sel_id, rhs')
513     in
514     mapDs ds_rbind rbinds                       `thenDs` \ rbinds' ->
515     let
516         record_in_ty               = coreExprType record_expr'
517         (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
518         (_,     out_inst_tys, _)   = splitAlgTyConApp record_out_ty
519         cons_to_upd                = filter has_all_fields cons
520
521         -- initial_args are passed to every constructor
522         initial_args            = map Type out_inst_tys ++ map Var dicts
523                 
524         mk_val_arg field old_arg_id 
525           = case [rhs | (f, rhs) <- rbinds', field == f] of
526               (rhs:rest) -> ASSERT(null rest) rhs
527               []         -> Var old_arg_id
528
529         mk_alt con
530           = newSysLocalsDs (dataConArgTys con in_inst_tys)      `thenDs` \ arg_ids ->
531             let 
532                 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
533                                         (dataConFieldLabels con) arg_ids
534                 rhs = mkApps (mkApps (Var (dataConId con)) initial_args) val_args
535             in
536             returnDs (DataCon con, arg_ids, rhs)
537
538         mk_default
539           | length cons_to_upd == length cons 
540           = returnDs []
541           | otherwise                       
542           = mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty ""      `thenDs` \ err ->
543             returnDs [(DEFAULT, [], err)]
544     in
545         -- Record stuff doesn't work for existentials
546     ASSERT( all (not . isExistentialDataCon) cons )
547
548     newSysLocalDs record_in_ty  `thenDs` \ case_bndr ->
549     mapDs mk_alt cons_to_upd    `thenDs` \ alts ->
550     mk_default                  `thenDs` \ deflt ->
551
552     returnDs (Case record_expr' case_bndr (alts ++ deflt))
553   where
554     has_all_fields :: DataCon -> Bool
555     has_all_fields con_id 
556       = all ok rbinds
557       where
558         con_fields        = dataConFieldLabels con_id
559         ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
560 \end{code}
561
562 Dictionary lambda and application
563 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
564 @DictLam@ and @DictApp@ turn into the regular old things.
565 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
566 complicated; reminiscent of fully-applied constructors.
567 \begin{code}
568 dsExpr (DictLam dictvars expr)
569   = dsExpr expr `thenDs` \ core_expr ->
570     returnDs (mkLams dictvars core_expr)
571
572 ------------------
573
574 dsExpr (DictApp expr dicts)     -- becomes a curried application
575   = dsExpr expr                 `thenDs` \ core_expr ->
576     returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
577 \end{code}
578
579 \begin{code}
580
581 #ifdef DEBUG
582 -- HsSyn constructs that just shouldn't be here:
583 dsExpr (HsDo _ _ _)         = panic "dsExpr:HsDo"
584 dsExpr (ExplicitList _)     = panic "dsExpr:ExplicitList"
585 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
586 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
587 #endif
588
589 out_of_range_msg                           -- ditto
590   = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
591 \end{code}
592
593 %--------------------------------------------------------------------
594
595 Basically does the translation given in the Haskell~1.3 report:
596
597 \begin{code}
598 dsDo    :: StmtCtxt
599         -> [TypecheckedStmt]
600         -> Id           -- id for: return m
601         -> Id           -- id for: (>>=) m
602         -> Id           -- id for: fail m
603         -> Type         -- Element type; the whole expression has type (m t)
604         -> DsM CoreExpr
605
606 dsDo do_or_lc stmts return_id then_id fail_id result_ty
607   = let
608         (_, b_ty) = splitAppTy result_ty        -- result_ty must be of the form (m b)
609         
610         go [ReturnStmt expr] 
611           = dsExpr expr                 `thenDs` \ expr2 ->
612             returnDs (mkApps (Var return_id) [Type b_ty, expr2])
613     
614         go (GuardStmt expr locn : stmts)
615           = do_expr expr locn                   `thenDs` \ expr2 ->
616             go stmts                            `thenDs` \ rest ->
617             let msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn) in
618             returnDs (mkIfThenElse expr2 
619                                    rest 
620                                    (App (App (Var fail_id) 
621                                              (Type b_ty))
622                                              (mkLit (mkStrLit msg stringTy))))
623     
624         go (ExprStmt expr locn : stmts)
625           = do_expr expr locn           `thenDs` \ expr2 ->
626             let
627                 (_, a_ty) = splitAppTy (coreExprType expr2)     -- Must be of form (m a)
628             in
629             if null stmts then
630                 returnDs expr2
631             else
632                 go stmts                `thenDs` \ rest  ->
633                 newSysLocalDs a_ty              `thenDs` \ ignored_result_id ->
634                 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2, 
635                                                 Lam ignored_result_id rest])
636     
637         go (LetStmt binds : stmts )
638           = go stmts            `thenDs` \ rest   ->
639             dsLet binds rest
640             
641         go (BindStmt pat expr locn : stmts)
642           = putSrcLocDs locn $
643             dsExpr expr            `thenDs` \ expr2 ->
644             let
645                 (_, a_ty)  = splitAppTy (coreExprType expr2)    -- Must be of form (m a)
646                 fail_expr  = HsApp (TyApp (HsVar fail_id) [b_ty]) (HsLitOut (HsString (_PK_ msg)) stringTy)
647                 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
648                 main_match = mkSimpleMatch [pat] 
649                                            (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty locn)
650                                            (Just result_ty) locn
651                 the_matches
652                   | failureFreePat pat = [main_match]
653                   | otherwise          =
654                       [ main_match
655                       , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
656                       ]
657             in
658             matchWrapper DoBindMatch the_matches match_msg
659                                 `thenDs` \ (binders, matching_code) ->
660             returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
661                                             mkLams binders matching_code])
662     in
663     go stmts
664
665   where
666     do_expr expr locn = putSrcLocDs locn (dsExpr expr)
667
668     match_msg = case do_or_lc of
669                         DoStmt   -> "`do' statement"
670                         ListComp -> "comprehension"
671 \end{code}
672
673 \begin{code}
674 var_pat (WildPat _) = True
675 var_pat (VarPat _) = True
676 var_pat _ = False
677 \end{code}
678