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