[project @ 1999-05-11 16:37:29 by keithw]
[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, isNotUsgTy, unUsgTy,
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                 ASSERT( isNotUsgTy ty )
402                 returnDs (mkConApp consDataCon [Type ty, core_x, core_xs])
403
404 dsExpr (ExplicitTuple expr_list boxed)
405   = mapDs dsExpr expr_list        `thenDs` \ core_exprs  ->
406     returnDs (mkConApp ((if boxed 
407                             then tupleCon 
408                             else unboxedTupleCon) (length expr_list))
409                 (map (Type . unUsgTy . coreExprType) core_exprs ++ core_exprs))
410                 -- the above unUsgTy is *required* -- KSW 1999-04-07
411
412 dsExpr (HsCon con_id [ty] [arg])
413   | isNewTyCon tycon
414   = dsExpr arg               `thenDs` \ arg' ->
415     returnDs (Note (Coerce result_ty (unUsgTy (coreExprType arg'))) arg')
416   where
417     result_ty = mkTyConApp tycon [ty]
418     tycon     = dataConTyCon con_id
419
420 dsExpr (HsCon con_id tys args)
421   = mapDs dsExpr args             `thenDs` \ args2  ->
422     ASSERT( all isNotUsgTy tys )
423     returnDs (mkConApp con_id (map Type tys ++ args2))
424
425 dsExpr (ArithSeqOut expr (From from))
426   = dsExpr expr           `thenDs` \ expr2 ->
427     dsExpr from           `thenDs` \ from2 ->
428     returnDs (App expr2 from2)
429
430 dsExpr (ArithSeqOut expr (FromTo from two))
431   = dsExpr expr           `thenDs` \ expr2 ->
432     dsExpr from           `thenDs` \ from2 ->
433     dsExpr two            `thenDs` \ two2 ->
434     returnDs (mkApps expr2 [from2, two2])
435
436 dsExpr (ArithSeqOut expr (FromThen from thn))
437   = dsExpr expr           `thenDs` \ expr2 ->
438     dsExpr from           `thenDs` \ from2 ->
439     dsExpr thn            `thenDs` \ thn2 ->
440     returnDs (mkApps expr2 [from2, thn2])
441
442 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
443   = dsExpr expr           `thenDs` \ expr2 ->
444     dsExpr from           `thenDs` \ from2 ->
445     dsExpr thn            `thenDs` \ thn2 ->
446     dsExpr two            `thenDs` \ two2 ->
447     returnDs (mkApps expr2 [from2, thn2, two2])
448 \end{code}
449
450 Record construction and update
451 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
452 For record construction we do this (assuming T has three arguments)
453
454         T { op2 = e }
455 ==>
456         let err = /\a -> recConErr a 
457         T (recConErr t1 "M.lhs/230/op1") 
458           e 
459           (recConErr t1 "M.lhs/230/op3")
460
461 recConErr then converts its arugment string into a proper message
462 before printing it as
463
464         M.lhs, line 230: missing field op1 was evaluated
465
466
467 \begin{code}
468 dsExpr (RecordConOut data_con con_expr rbinds)
469   = dsExpr con_expr     `thenDs` \ con_expr' ->
470     let
471         (arg_tys, _) = splitFunTys (coreExprType con_expr')
472
473         mk_arg (arg_ty, lbl)
474           = case [rhs | (sel_id,rhs,_) <- rbinds,
475                         lbl == recordSelectorFieldLabel sel_id] of
476               (rhs:rhss) -> ASSERT( null rhss )
477                             dsExpr rhs
478               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
479     in
480     mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys (dataConFieldLabels data_con)) `thenDs` \ con_args ->
481     returnDs (mkApps con_expr' con_args)
482 \end{code}
483
484 Record update is a little harder. Suppose we have the decl:
485
486         data T = T1 {op1, op2, op3 :: Int}
487                | T2 {op4, op2 :: Int}
488                | T3
489
490 Then we translate as follows:
491
492         r { op2 = e }
493 ===>
494         let op2 = e in
495         case r of
496           T1 op1 _ op3 -> T1 op1 op2 op3
497           T2 op4 _     -> T2 op4 op2
498           other        -> recUpdError "M.lhs/230"
499
500 It's important that we use the constructor Ids for T1, T2 etc on the
501 RHSs, and do not generate a Core Con directly, because the constructor
502 might do some argument-evaluation first; and may have to throw away some
503 dictionaries.
504
505 \begin{code}
506 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
507   = dsExpr record_expr          `thenDs` \ record_expr' ->
508
509         -- Desugar the rbinds, and generate let-bindings if
510         -- necessary so that we don't lose sharing
511
512     let
513         ds_rbind (sel_id, rhs, pun_flag)
514           = dsExpr rhs                          `thenDs` \ rhs' ->
515             returnDs (recordSelectorFieldLabel sel_id, rhs')
516     in
517     mapDs ds_rbind rbinds                       `thenDs` \ rbinds' ->
518     let
519         record_in_ty               = coreExprType record_expr'
520         (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
521         (_,     out_inst_tys, _)   = splitAlgTyConApp record_out_ty
522         cons_to_upd                = filter has_all_fields cons
523
524         -- initial_args are passed to every constructor
525         initial_args            = map Type out_inst_tys ++ map Var dicts
526                 
527         mk_val_arg field old_arg_id 
528           = case [rhs | (f, rhs) <- rbinds', field == f] of
529               (rhs:rest) -> ASSERT(null rest) rhs
530               []         -> Var old_arg_id
531
532         mk_alt con
533           = newSysLocalsDs (dataConArgTys con in_inst_tys)      `thenDs` \ arg_ids ->
534             let 
535                 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
536                                         (dataConFieldLabels con) arg_ids
537                 rhs = mkApps (mkApps (Var (dataConId con)) initial_args) val_args
538             in
539             returnDs (DataCon con, arg_ids, rhs)
540
541         mk_default
542           | length cons_to_upd == length cons 
543           = returnDs []
544           | otherwise                       
545           = mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty ""      `thenDs` \ err ->
546             returnDs [(DEFAULT, [], err)]
547     in
548         -- Record stuff doesn't work for existentials
549     ASSERT( all (not . isExistentialDataCon) cons )
550
551     newSysLocalDs record_in_ty  `thenDs` \ case_bndr ->
552     mapDs mk_alt cons_to_upd    `thenDs` \ alts ->
553     mk_default                  `thenDs` \ deflt ->
554
555     returnDs (Case record_expr' case_bndr (alts ++ deflt))
556   where
557     has_all_fields :: DataCon -> Bool
558     has_all_fields con_id 
559       = all ok rbinds
560       where
561         con_fields        = dataConFieldLabels con_id
562         ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
563 \end{code}
564
565 Dictionary lambda and application
566 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
567 @DictLam@ and @DictApp@ turn into the regular old things.
568 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
569 complicated; reminiscent of fully-applied constructors.
570 \begin{code}
571 dsExpr (DictLam dictvars expr)
572   = dsExpr expr `thenDs` \ core_expr ->
573     returnDs (mkLams dictvars core_expr)
574
575 ------------------
576
577 dsExpr (DictApp expr dicts)     -- becomes a curried application
578   = dsExpr expr                 `thenDs` \ core_expr ->
579     returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
580 \end{code}
581
582 \begin{code}
583
584 #ifdef DEBUG
585 -- HsSyn constructs that just shouldn't be here:
586 dsExpr (HsDo _ _ _)         = panic "dsExpr:HsDo"
587 dsExpr (ExplicitList _)     = panic "dsExpr:ExplicitList"
588 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
589 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
590 #endif
591
592 out_of_range_msg                           -- ditto
593   = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
594 \end{code}
595
596 %--------------------------------------------------------------------
597
598 Basically does the translation given in the Haskell~1.3 report:
599
600 \begin{code}
601 dsDo    :: StmtCtxt
602         -> [TypecheckedStmt]
603         -> Id           -- id for: return m
604         -> Id           -- id for: (>>=) m
605         -> Id           -- id for: fail m
606         -> Type         -- Element type; the whole expression has type (m t)
607         -> DsM CoreExpr
608
609 dsDo do_or_lc stmts return_id then_id fail_id result_ty
610   = let
611         (_, b_ty) = splitAppTy result_ty        -- result_ty must be of the form (m b)
612         
613         go [ReturnStmt expr] 
614           = dsExpr expr                 `thenDs` \ expr2 ->
615             returnDs (mkApps (Var return_id) [Type b_ty, expr2])
616     
617         go (GuardStmt expr locn : stmts)
618           = do_expr expr locn                   `thenDs` \ expr2 ->
619             go stmts                            `thenDs` \ rest ->
620             let msg = ASSERT( isNotUsgTy b_ty )
621                       "Pattern match failure in do expression, " ++ showSDoc (ppr locn) in
622             returnDs (mkIfThenElse expr2 
623                                    rest 
624                                    (App (App (Var fail_id) 
625                                              (Type b_ty))
626                                              (mkLit (mkStrLit msg stringTy))))
627     
628         go (ExprStmt expr locn : stmts)
629           = do_expr expr locn           `thenDs` \ expr2 ->
630             let
631                 (_, a_ty) = splitAppTy (coreExprType expr2)     -- Must be of form (m a)
632             in
633             if null stmts then
634                 returnDs expr2
635             else
636                 go stmts                `thenDs` \ rest  ->
637                 newSysLocalDs a_ty              `thenDs` \ ignored_result_id ->
638                 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2, 
639                                                 Lam ignored_result_id rest])
640     
641         go (LetStmt binds : stmts )
642           = go stmts            `thenDs` \ rest   ->
643             dsLet binds rest
644             
645         go (BindStmt pat expr locn : stmts)
646           = putSrcLocDs locn $
647             dsExpr expr            `thenDs` \ expr2 ->
648             let
649                 (_, a_ty)  = splitAppTy (coreExprType expr2)    -- Must be of form (m a)
650                 fail_expr  = HsApp (TyApp (HsVar fail_id) [b_ty]) (HsLitOut (HsString (_PK_ msg)) stringTy)
651                 msg = ASSERT2( isNotUsgTy a_ty, ppr a_ty )
652                       ASSERT2( isNotUsgTy b_ty, ppr b_ty )
653                       "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
654                 main_match = mkSimpleMatch [pat] 
655                                            (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty locn)
656                                            (Just result_ty) locn
657                 the_matches
658                   | failureFreePat pat = [main_match]
659                   | otherwise          =
660                       [ main_match
661                       , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
662                       ]
663             in
664             matchWrapper DoBindMatch the_matches match_msg
665                                 `thenDs` \ (binders, matching_code) ->
666             returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
667                                             mkLams binders matching_code])
668     in
669     go stmts
670
671   where
672     do_expr expr locn = putSrcLocDs locn (dsExpr expr)
673
674     match_msg = case do_or_lc of
675                         DoStmt   -> "`do' statement"
676                         ListComp -> "comprehension"
677 \end{code}
678
679 \begin{code}
680 var_pat (WildPat _) = True
681 var_pat (VarPat _) = True
682 var_pat _ = False
683 \end{code}
684