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