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