[project @ 1999-05-18 15:03:54 by simonpj]
[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 op1 was evaluated
461
462
463 \begin{code}
464 dsExpr (RecordConOut data_con con_expr rbinds)
465   = dsExpr con_expr     `thenDs` \ con_expr' ->
466     let
467         (arg_tys, _) = splitFunTys (coreExprType con_expr')
468
469         mk_arg (arg_ty, lbl)
470           = case [rhs | (sel_id,rhs,_) <- rbinds,
471                         lbl == recordSelectorFieldLabel sel_id] of
472               (rhs:rhss) -> ASSERT( null rhss )
473                             dsExpr rhs
474               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
475     in
476     mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys (dataConFieldLabels data_con)) `thenDs` \ con_args ->
477     returnDs (mkApps con_expr' con_args)
478 \end{code}
479
480 Record update is a little harder. Suppose we have the decl:
481
482         data T = T1 {op1, op2, op3 :: Int}
483                | T2 {op4, op2 :: Int}
484                | T3
485
486 Then we translate as follows:
487
488         r { op2 = e }
489 ===>
490         let op2 = e in
491         case r of
492           T1 op1 _ op3 -> T1 op1 op2 op3
493           T2 op4 _     -> T2 op4 op2
494           other        -> recUpdError "M.lhs/230"
495
496 It's important that we use the constructor Ids for T1, T2 etc on the
497 RHSs, and do not generate a Core Con directly, because the constructor
498 might do some argument-evaluation first; and may have to throw away some
499 dictionaries.
500
501 \begin{code}
502 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
503   = dsExpr record_expr          `thenDs` \ record_expr' ->
504
505         -- Desugar the rbinds, and generate let-bindings if
506         -- necessary so that we don't lose sharing
507
508     let
509         ds_rbind (sel_id, rhs, pun_flag)
510           = dsExpr rhs                          `thenDs` \ rhs' ->
511             returnDs (recordSelectorFieldLabel sel_id, rhs')
512     in
513     mapDs ds_rbind rbinds                       `thenDs` \ rbinds' ->
514     let
515         record_in_ty               = coreExprType record_expr'
516         (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
517         (_,     out_inst_tys, _)   = splitAlgTyConApp record_out_ty
518         cons_to_upd                = filter has_all_fields cons
519
520         -- initial_args are passed to every constructor
521         initial_args            = map Type out_inst_tys ++ map Var dicts
522                 
523         mk_val_arg field old_arg_id 
524           = case [rhs | (f, rhs) <- rbinds', field == f] of
525               (rhs:rest) -> ASSERT(null rest) rhs
526               []         -> Var old_arg_id
527
528         mk_alt con
529           = newSysLocalsDs (dataConArgTys con in_inst_tys)      `thenDs` \ arg_ids ->
530             let 
531                 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
532                                         (dataConFieldLabels con) arg_ids
533                 rhs = mkApps (mkApps (Var (dataConId con)) initial_args) val_args
534             in
535             returnDs (DataCon con, arg_ids, rhs)
536
537         mk_default
538           | length cons_to_upd == length cons 
539           = returnDs []
540           | otherwise                       
541           = mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty ""      `thenDs` \ err ->
542             returnDs [(DEFAULT, [], err)]
543     in
544         -- Record stuff doesn't work for existentials
545     ASSERT( all (not . isExistentialDataCon) cons )
546
547     newSysLocalDs record_in_ty  `thenDs` \ case_bndr ->
548     mapDs mk_alt cons_to_upd    `thenDs` \ alts ->
549     mk_default                  `thenDs` \ deflt ->
550
551     returnDs (Case record_expr' case_bndr (alts ++ deflt))
552   where
553     has_all_fields :: DataCon -> Bool
554     has_all_fields con_id 
555       = all ok rbinds
556       where
557         con_fields        = dataConFieldLabels con_id
558         ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
559 \end{code}
560
561 Dictionary lambda and application
562 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
563 @DictLam@ and @DictApp@ turn into the regular old things.
564 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
565 complicated; reminiscent of fully-applied constructors.
566 \begin{code}
567 dsExpr (DictLam dictvars expr)
568   = dsExpr expr `thenDs` \ core_expr ->
569     returnDs (mkLams dictvars core_expr)
570
571 ------------------
572
573 dsExpr (DictApp expr dicts)     -- becomes a curried application
574   = dsExpr expr                 `thenDs` \ core_expr ->
575     returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
576 \end{code}
577
578 \begin{code}
579
580 #ifdef DEBUG
581 -- HsSyn constructs that just shouldn't be here:
582 dsExpr (HsDo _ _ _)         = panic "dsExpr:HsDo"
583 dsExpr (ExplicitList _)     = panic "dsExpr:ExplicitList"
584 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
585 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
586 #endif
587
588 out_of_range_msg                           -- ditto
589   = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
590 \end{code}
591
592 %--------------------------------------------------------------------
593
594 Basically does the translation given in the Haskell~1.3 report:
595
596 \begin{code}
597 dsDo    :: StmtCtxt
598         -> [TypecheckedStmt]
599         -> Id           -- id for: return m
600         -> Id           -- id for: (>>=) m
601         -> Id           -- id for: fail m
602         -> Type         -- Element type; the whole expression has type (m t)
603         -> DsM CoreExpr
604
605 dsDo do_or_lc stmts return_id then_id fail_id result_ty
606   = let
607         (_, b_ty) = splitAppTy result_ty        -- result_ty must be of the form (m b)
608         
609         go [ReturnStmt expr] 
610           = dsExpr expr                 `thenDs` \ expr2 ->
611             returnDs (mkApps (Var return_id) [Type b_ty, expr2])
612     
613         go (GuardStmt expr locn : stmts)
614           = do_expr expr locn                   `thenDs` \ expr2 ->
615             go stmts                            `thenDs` \ rest ->
616             let msg = ASSERT( isNotUsgTy b_ty )
617                       "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 = ASSERT2( isNotUsgTy a_ty, ppr a_ty )
648                       ASSERT2( isNotUsgTy b_ty, ppr b_ty )
649                       "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
650                 main_match = mkSimpleMatch [pat] 
651                                            (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty locn)
652                                            (Just result_ty) locn
653                 the_matches
654                   | failureFreePat pat = [main_match]
655                   | otherwise          =
656                       [ main_match
657                       , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
658                       ]
659             in
660             matchWrapper DoBindMatch the_matches match_msg
661                                 `thenDs` \ (binders, matching_code) ->
662             returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
663                                             mkLams binders matching_code])
664     in
665     go stmts
666
667   where
668     do_expr expr locn = putSrcLocDs locn (dsExpr expr)
669
670     match_msg = case do_or_lc of
671                         DoStmt   -> "`do' statement"
672                         ListComp -> "comprehension"
673 \end{code}
674
675 \begin{code}
676 var_pat (WildPat _) = True
677 var_pat (VarPat _) = True
678 var_pat _ = False
679 \end{code}
680