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