[project @ 2000-03-27 13:24:12 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 import CoreUtils        ( exprType, mkIfThenElse, bindNonRec )
24
25 import DsMonad
26 import DsBinds          ( dsMonoBinds, AutoScc(..) )
27 import DsGRHSs          ( dsGuarded )
28 import DsCCall          ( dsCCall )
29 import DsListComp       ( dsListComp )
30 import DsUtils          ( mkErrorAppDs, mkDsLets, mkConsExpr, mkNilExpr )
31 import Match            ( matchWrapper, matchSimply )
32
33 import CostCentre       ( mkUserCC )
34 import FieldLabel       ( FieldLabel )
35 import Id               ( Id, idType, recordSelectorFieldLabel )
36 import DataCon          ( DataCon, dataConId, dataConTyCon, dataConArgTys, dataConFieldLabels )
37 import PrelInfo         ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID, addr2IntegerId )
38 import TyCon            ( isNewTyCon )
39 import DataCon          ( isExistentialDataCon )
40 import Literal          ( Literal(..), inIntRange )
41 import Type             ( splitFunTys, mkTyConApp,
42                           splitAlgTyConApp, splitAlgTyConApp_maybe, splitTyConApp_maybe, 
43                           isNotUsgTy, unUsgTy,
44                           splitAppTy, isUnLiftedType, Type
45                         )
46 import PprType          ( {- instance Outputable Type -} )
47 import TysWiredIn       ( tupleCon, unboxedTupleCon,
48                           listTyCon, mkListTy,
49                           charDataCon, charTy, stringTy,
50                           smallIntegerDataCon, isIntegerTy
51                         )
52 import BasicTypes       ( RecFlag(..) )
53 import Maybes           ( maybeToBool )
54 import Unique           ( Uniquable(..), ratioTyConKey )
55 import Util             ( zipEqual, zipWithEqual )
56 import Outputable
57
58 import Ratio            ( numerator, denominator )
59 \end{code}
60
61
62 %************************************************************************
63 %*                                                                      *
64 \subsection{dsLet}
65 %*                                                                      *
66 %************************************************************************
67
68 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
69 and transforming it into one for the let-bindings enclosing the body.
70
71 This may seem a bit odd, but (source) let bindings can contain unboxed
72 binds like
73 \begin{verbatim}
74         C x# = e
75 \end{verbatim}
76 This must be transformed to a case expression and, if the type has
77 more than one constructor, may fail.
78
79 \begin{code}
80 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
81
82 dsLet EmptyBinds body
83   = returnDs body
84
85 dsLet (ThenBinds b1 b2) body
86   = dsLet b2 body       `thenDs` \ body' ->
87     dsLet b1 body'
88   
89 -- Special case for bindings which bind unlifted variables
90 -- Silently ignore INLINE pragmas...
91 dsLet (MonoBind (AbsBinds [] [] binder_triples inlines
92                           (PatMonoBind pat grhss loc)) sigs is_rec) body
93   | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
94   = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
95     putSrcLocDs loc                     $
96     dsGuarded grhss                     `thenDs` \ rhs ->
97     let
98         body' = foldr bind body binder_triples
99         bind (tyvars, g, l) body = ASSERT( null tyvars )
100                                    bindNonRec g (Var l) body
101     in
102     mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat))
103     `thenDs` \ error_expr ->
104     matchSimply rhs PatBindMatch pat body' error_expr
105   where
106     result_ty = exprType body
107
108 -- Ordinary case for bindings
109 dsLet (MonoBind binds sigs is_rec) body
110   = dsMonoBinds NoSccs binds []  `thenDs` \ prs ->
111     case is_rec of
112       Recursive    -> returnDs (Let (Rec prs) body)
113       NonRecursive -> returnDs (mkDsLets [NonRec b r | (b,r) <- prs] body)
114 \end{code}
115
116 %************************************************************************
117 %*                                                                      *
118 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
119 %*                                                                      *
120 %************************************************************************
121
122 \begin{code}
123 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
124
125 dsExpr e@(HsVar var) = returnDs (Var var)
126 dsExpr e@(HsIPVar var) = returnDs (Var var)
127 \end{code}
128
129 %************************************************************************
130 %*                                                                      *
131 \subsection[DsExpr-literals]{Literals}
132 %*                                                                      *
133 %************************************************************************
134
135 We give int/float literals type @Integer@ and @Rational@, respectively.
136 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
137 around them.
138
139 ToDo: put in range checks for when converting ``@i@''
140 (or should that be in the typechecker?)
141
142 For numeric literals, we try to detect there use at a standard type
143 (@Int@, @Float@, etc.) are directly put in the right constructor.
144 [NB: down with the @App@ conversion.]
145
146 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
147
148 \begin{code}
149 dsExpr (HsLitOut (HsString s) _)
150   | _NULL_ s
151   = returnDs (mkNilExpr charTy)
152
153   | _LENGTH_ s == 1
154   = let
155         the_char = mkConApp charDataCon [mkLit (MachChar (_HEAD_ s))]
156         the_nil  = mkNilExpr charTy
157         the_cons = mkConsExpr charTy the_char the_nil
158     in
159     returnDs the_cons
160
161
162 -- "_" => build (\ c n -> c 'c' n)      -- LATER
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 (mkIntegerLit i)
194
195
196 dsExpr (HsLitOut (HsFrac r) ty)
197   = returnDs (mkConApp ratio_data_con [Type integer_ty,
198                                        mkIntegerLit (numerator r),
199                                        mkIntegerLit (denominator r)])
200   where
201     (ratio_data_con, integer_ty)
202       = case (splitAlgTyConApp_maybe ty) of
203           Just (tycon, [i_ty], [con])
204             -> ASSERT(isIntegerTy i_ty && getUnique tycon == ratioTyConKey)
205                (con, i_ty)
206
207           _ -> (panic "ratio_data_con", panic "integer_ty")
208
209
210
211 -- others where we know what to do:
212
213 dsExpr (HsLitOut (HsIntPrim i) _) 
214   = returnDs (mkIntLit i)
215
216 dsExpr (HsLitOut (HsFloatPrim f) _)
217   = returnDs (mkLit (MachFloat f))
218
219 dsExpr (HsLitOut (HsDoublePrim d) _)
220   = returnDs (mkLit (MachDouble d))
221     -- ToDo: range checking needed!
222
223 dsExpr (HsLitOut (HsChar c) _)
224   = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
225
226 dsExpr (HsLitOut (HsCharPrim c) _)
227   = returnDs (mkLit (MachChar c))
228
229 dsExpr (HsLitOut (HsStringPrim s) _)
230   = returnDs (mkLit (MachStr s))
231
232 -- end of literals magic. --
233
234 dsExpr expr@(HsLam a_Match)
235   = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
236     returnDs (mkLams binders matching_code)
237
238 dsExpr expr@(HsApp fun arg)      
239   = dsExpr fun          `thenDs` \ core_fun ->
240     dsExpr arg          `thenDs` \ core_arg ->
241     returnDs (core_fun `App` core_arg)
242
243 \end{code}
244
245 Operator sections.  At first it looks as if we can convert
246 \begin{verbatim}
247         (expr op)
248 \end{verbatim}
249 to
250 \begin{verbatim}
251         \x -> op expr x
252 \end{verbatim}
253
254 But no!  expr might be a redex, and we can lose laziness badly this
255 way.  Consider
256 \begin{verbatim}
257         map (expr op) xs
258 \end{verbatim}
259 for example.  So we convert instead to
260 \begin{verbatim}
261         let y = expr in \x -> op y x
262 \end{verbatim}
263 If \tr{expr} is actually just a variable, say, then the simplifier
264 will sort it out.
265
266 \begin{code}
267 dsExpr (OpApp e1 op _ e2)
268   = dsExpr op                                           `thenDs` \ core_op ->
269     -- for the type of y, we need the type of op's 2nd argument
270     dsExpr e1                           `thenDs` \ x_core ->
271     dsExpr e2                           `thenDs` \ y_core ->
272     returnDs (mkApps core_op [x_core, y_core])
273     
274 dsExpr (SectionL expr op)
275   = dsExpr op                                           `thenDs` \ core_op ->
276     -- for the type of y, we need the type of op's 2nd argument
277     let
278         (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
279     in
280     dsExpr expr                         `thenDs` \ x_core ->
281     newSysLocalDs x_ty                  `thenDs` \ x_id ->
282     newSysLocalDs y_ty                  `thenDs` \ y_id ->
283
284     returnDs (bindNonRec x_id x_core $
285               Lam y_id (mkApps core_op [Var x_id, Var y_id]))
286
287 -- dsExpr (SectionR op expr)    -- \ x -> op x expr
288 dsExpr (SectionR op expr)
289   = dsExpr op                   `thenDs` \ core_op ->
290     -- for the type of x, we need the type of op's 2nd argument
291     let
292         (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
293     in
294     dsExpr expr                         `thenDs` \ y_core ->
295     newSysLocalDs x_ty                  `thenDs` \ x_id ->
296     newSysLocalDs y_ty                  `thenDs` \ y_id ->
297
298     returnDs (bindNonRec y_id y_core $
299               Lam x_id (mkApps core_op [Var x_id, Var y_id]))
300
301 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
302   = mapDs dsExpr args           `thenDs` \ core_args ->
303     dsCCall lbl core_args may_gc is_asm result_ty
304         -- dsCCall does all the unboxification, etc.
305
306 dsExpr (HsSCC cc expr)
307   = dsExpr expr                 `thenDs` \ core_expr ->
308     getModuleDs                 `thenDs` \ mod_name ->
309     returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
310
311 -- special case to handle unboxed tuple patterns.
312
313 dsExpr (HsCase discrim matches src_loc)
314  | all ubx_tuple_match matches
315  =  putSrcLocDs src_loc $
316     dsExpr discrim                        `thenDs` \ core_discrim ->
317     matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
318     case matching_code of
319         Case (Var x) bndr alts | x == discrim_var -> 
320                 returnDs (Case core_discrim bndr alts)
321         _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
322   where
323     ubx_tuple_match (Match _ [TuplePat ps False{-unboxed-}] _ _) = True
324     ubx_tuple_match _ = False
325
326 dsExpr (HsCase discrim matches src_loc)
327   = putSrcLocDs src_loc $
328     dsExpr discrim                        `thenDs` \ core_discrim ->
329     matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
330     returnDs (bindNonRec discrim_var core_discrim matching_code)
331
332 dsExpr (HsLet binds body)
333   = dsExpr body         `thenDs` \ body' ->
334     dsLet binds body'
335
336 dsExpr (HsWith expr binds)
337   = dsExpr expr         `thenDs` \ expr' ->
338     foldlDs dsIPBind expr' binds
339     where
340       dsIPBind body (n, e)
341         = dsExpr e      `thenDs` \ e' ->
342           returnDs (Let (NonRec n e') body)
343
344 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
345   | maybeToBool maybe_list_comp
346   =     -- Special case for list comprehensions
347     putSrcLocDs src_loc $
348     dsListComp stmts elt_ty
349
350   | otherwise
351   = putSrcLocDs src_loc $
352     dsDo do_or_lc stmts return_id then_id fail_id result_ty
353   where
354     maybe_list_comp 
355         = case (do_or_lc, splitTyConApp_maybe result_ty) of
356             (ListComp, Just (tycon, [elt_ty]))
357                   | tycon == listTyCon
358                  -> Just elt_ty
359             other -> Nothing
360         -- We need the ListComp form to use deListComp (rather than the "do" form)
361         -- because the "return" in a do block is a call to "PrelBase.return", and
362         -- not a ReturnStmt.  Only the ListComp form has ReturnStmts
363
364     Just elt_ty = maybe_list_comp
365
366 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
367   = putSrcLocDs src_loc $
368     dsExpr guard_expr   `thenDs` \ core_guard ->
369     dsExpr then_expr    `thenDs` \ core_then ->
370     dsExpr else_expr    `thenDs` \ core_else ->
371     returnDs (mkIfThenElse core_guard core_then core_else)
372 \end{code}
373
374
375 \noindent
376 \underline{\bf Type lambda and application}
377 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~
378 \begin{code}
379 dsExpr (TyLam tyvars expr)
380   = dsExpr expr `thenDs` \ core_expr ->
381     returnDs (mkLams tyvars core_expr)
382
383 dsExpr (TyApp expr tys)
384   = dsExpr expr         `thenDs` \ core_expr ->
385     returnDs (mkTyApps core_expr tys)
386 \end{code}
387
388
389 \noindent
390 \underline{\bf Various data construction things}
391 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
392 \begin{code}
393 dsExpr (ExplicitListOut ty xs)
394   = go xs
395   where
396     list_ty   = mkListTy ty
397
398     go []     = returnDs (mkNilExpr ty)
399     go (x:xs) = dsExpr x                                `thenDs` \ core_x ->
400                 go xs                                   `thenDs` \ core_xs ->
401                 ASSERT( isNotUsgTy ty )
402                 returnDs (mkConsExpr ty core_x core_xs)
403
404 dsExpr (ExplicitTuple expr_list boxed)
405   = mapDs dsExpr expr_list        `thenDs` \ core_exprs  ->
406     returnDs (mkConApp ((if boxed 
407                             then tupleCon 
408                             else unboxedTupleCon) (length expr_list))
409                 (map (Type . unUsgTy . exprType) core_exprs ++ core_exprs))
410                 -- the above unUsgTy is *required* -- KSW 1999-04-07
411
412 dsExpr (ArithSeqOut expr (From from))
413   = dsExpr expr           `thenDs` \ expr2 ->
414     dsExpr from           `thenDs` \ from2 ->
415     returnDs (App expr2 from2)
416
417 dsExpr (ArithSeqOut expr (FromTo from two))
418   = dsExpr expr           `thenDs` \ expr2 ->
419     dsExpr from           `thenDs` \ from2 ->
420     dsExpr two            `thenDs` \ two2 ->
421     returnDs (mkApps expr2 [from2, two2])
422
423 dsExpr (ArithSeqOut expr (FromThen from thn))
424   = dsExpr expr           `thenDs` \ expr2 ->
425     dsExpr from           `thenDs` \ from2 ->
426     dsExpr thn            `thenDs` \ thn2 ->
427     returnDs (mkApps expr2 [from2, thn2])
428
429 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
430   = dsExpr expr           `thenDs` \ expr2 ->
431     dsExpr from           `thenDs` \ from2 ->
432     dsExpr thn            `thenDs` \ thn2 ->
433     dsExpr two            `thenDs` \ two2 ->
434     returnDs (mkApps expr2 [from2, thn2, two2])
435 \end{code}
436
437 \noindent
438 \underline{\bf Record construction and update}
439 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
440 For record construction we do this (assuming T has three arguments)
441 \begin{verbatim}
442         T { op2 = e }
443 ==>
444         let err = /\a -> recConErr a 
445         T (recConErr t1 "M.lhs/230/op1") 
446           e 
447           (recConErr t1 "M.lhs/230/op3")
448 \end{verbatim}
449 @recConErr@ then converts its arugment string into a proper message
450 before printing it as
451 \begin{verbatim}
452         M.lhs, line 230: missing field op1 was evaluated
453 \end{verbatim}
454
455 We also handle @C{}@ as valid construction syntax for an unlabelled
456 constructor @C@, setting all of @C@'s fields to bottom.
457
458 \begin{code}
459 dsExpr (RecordConOut data_con con_expr rbinds)
460   = dsExpr con_expr     `thenDs` \ con_expr' ->
461     let
462         (arg_tys, _) = splitFunTys (exprType con_expr')
463
464         mk_arg (arg_ty, lbl)
465           = case [rhs | (sel_id,rhs,_) <- rbinds,
466                         lbl == recordSelectorFieldLabel sel_id] of
467               (rhs:rhss) -> ASSERT( null rhss )
468                             dsExpr rhs
469               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
470         unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
471
472         labels = dataConFieldLabels data_con
473     in
474
475     (if null labels
476         then mapDs unlabelled_bottom arg_tys
477         else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
478         `thenDs` \ con_args ->
479
480     returnDs (mkApps con_expr' con_args)
481 \end{code}
482
483 Record update is a little harder. Suppose we have the decl:
484 \begin{verbatim}
485         data T = T1 {op1, op2, op3 :: Int}
486                | T2 {op4, op2 :: Int}
487                | T3
488 \end{verbatim}
489 Then we translate as follows:
490 \begin{verbatim}
491         r { op2 = e }
492 ===>
493         let op2 = e in
494         case r of
495           T1 op1 _ op3 -> T1 op1 op2 op3
496           T2 op4 _     -> T2 op4 op2
497           other        -> recUpdError "M.lhs/230"
498 \end{verbatim}
499 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
500 RHSs, and do not generate a Core constructor application directly, because the constructor
501 might do some argument-evaluation first; and may have to throw away some
502 dictionaries.
503
504 \begin{code}
505 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
506   = getSrcLocDs         `thenDs` \ src_loc ->
507     dsExpr record_expr          `thenDs` \ record_expr' ->
508
509         -- Desugar the rbinds, and generate let-bindings if
510         -- necessary so that we don't lose sharing
511
512     let
513         record_in_ty               = exprType record_expr'
514         (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
515         (_,     out_inst_tys, _)   = splitAlgTyConApp record_out_ty
516         cons_to_upd                = filter has_all_fields cons
517
518         mk_val_arg field old_arg_id 
519           = case [rhs | (sel_id, rhs, _) <- rbinds, 
520                         field == recordSelectorFieldLabel sel_id] of
521               (rhs:rest) -> ASSERT(null rest) rhs
522               []         -> HsVar old_arg_id
523
524         mk_alt con
525           = newSysLocalsDs (dataConArgTys con in_inst_tys)      `thenDs` \ arg_ids ->
526                 -- This call to dataConArgTys won't work for existentials
527             let 
528                 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
529                                         (dataConFieldLabels con) arg_ids
530                 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConId con)) 
531                                                   out_inst_tys)
532                                            dicts)
533                                   val_args
534             in
535             returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
536                                     rhs
537                                     (Just record_out_ty)
538                                     src_loc)
539     in
540         -- Record stuff doesn't work for existentials
541     ASSERT( all (not . isExistentialDataCon) cons )
542
543         -- It's important to generate the match with matchWrapper,
544         -- and the right hand sides with applications of the wrapper Id
545         -- so that everything works when we are doing fancy unboxing on the
546         -- constructor aguments.
547     mapDs mk_alt cons_to_upd                            `thenDs` \ alts ->
548     matchWrapper RecUpdMatch alts "record update"       `thenDs` \ ([discrim_var], matching_code) ->
549
550     returnDs (bindNonRec discrim_var record_expr' matching_code)
551
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
562 \noindent
563 \underline{\bf Dictionary lambda and application}
564 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
565 @DictLam@ and @DictApp@ turn into the regular old things.
566 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
567 complicated; reminiscent of fully-applied constructors.
568 \begin{code}
569 dsExpr (DictLam dictvars expr)
570   = dsExpr expr `thenDs` \ core_expr ->
571     returnDs (mkLams dictvars core_expr)
572
573 ------------------
574
575 dsExpr (DictApp expr dicts)     -- becomes a curried application
576   = dsExpr expr                 `thenDs` \ core_expr ->
577     returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
578 \end{code}
579
580 \begin{code}
581
582 #ifdef DEBUG
583 -- HsSyn constructs that just shouldn't be here:
584 dsExpr (HsDo _ _ _)         = panic "dsExpr:HsDo"
585 dsExpr (ExplicitList _)     = panic "dsExpr:ExplicitList"
586 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
587 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
588 #endif
589
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                                              (mkStringLit msg)))
623     
624         go (ExprStmt expr locn : stmts)
625           = do_expr expr locn           `thenDs` \ expr2 ->
626             let
627                 (_, a_ty) = splitAppTy (exprType 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 (exprType expr2) -- Must be of form (m a)
646                 fail_expr  = HsApp (TyApp (HsVar fail_id) [b_ty])
647                                    (HsLitOut (HsString (_PK_ msg)) stringTy)
648                 msg = ASSERT2( isNotUsgTy a_ty, ppr a_ty )
649                       ASSERT2( isNotUsgTy b_ty, ppr b_ty )
650                       "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
651                 main_match = mkSimpleMatch [pat] 
652                                            (HsDoOut do_or_lc stmts return_id then_id
653                                                     fail_id result_ty locn)
654                                            (Just result_ty) locn
655                 the_matches
656                   | failureFreePat pat = [main_match]
657                   | otherwise          =
658                       [ main_match
659                       , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
660                       ]
661             in
662             matchWrapper DoBindMatch the_matches match_msg
663                                 `thenDs` \ (binders, matching_code) ->
664             returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
665                                             mkLams binders matching_code])
666     in
667     go stmts
668
669   where
670     do_expr expr locn = putSrcLocDs locn (dsExpr expr)
671
672     match_msg = case do_or_lc of
673                         DoStmt   -> "`do' statement"
674                         ListComp -> "comprehension"
675 \end{code}
676
677 \begin{code}
678 var_pat (WildPat _) = True
679 var_pat (VarPat _) = True
680 var_pat _ = False
681 \end{code}
682
683 \begin{code}
684 mkIntegerLit :: Integer -> CoreExpr
685 mkIntegerLit i
686   | inIntRange i        -- Small enough, so start from an Int
687   = mkConApp smallIntegerDataCon [mkIntLit i]
688
689   | otherwise           -- Big, so start from a string
690   = App (Var addr2IntegerId) (Lit (MachStr (_PK_ (show i))))
691 \end{code}
692