[project @ 2002-02-11 08:20:38 by chak]
[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(..), HsMatchContext(..), HsDoContext(..), 
15                           Match(..), HsBinds(..), MonoBinds(..), 
16                           mkSimpleMatch 
17                         )
18 import TcHsSyn          ( TypecheckedHsExpr, TypecheckedHsBinds, TypecheckedStmt, outPatType )
19
20 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
21 --     needs to see source types (newtypes etc), and sometimes not
22 --     So WATCH OUT; check each use of split*Ty functions.
23 -- Sigh.  This is a pain.
24
25 import TcType           ( tcSplitAppTy, tcSplitFunTys, tcSplitTyConApp_maybe, tcTyConAppArgs,
26                           isIntegerTy, tcSplitTyConApp, isUnLiftedType, Type )
27 import Type             ( splitFunTys )
28 import CoreSyn
29 import CoreUtils        ( exprType, mkIfThenElse, bindNonRec )
30
31 import DsMonad
32 import DsBinds          ( dsMonoBinds, AutoScc(..) )
33 import DsGRHSs          ( dsGuarded )
34 import DsCCall          ( dsCCall, resultWrapper )
35 import DsListComp       ( dsListComp, dsPArrComp )
36 import DsUtils          ( mkErrorAppDs, mkStringLit, mkStringLitFS, 
37                           mkConsExpr, mkNilExpr, mkIntegerLit
38                         )
39 import Match            ( matchWrapper, matchSimply )
40
41 import FieldLabel       ( FieldLabel, fieldLabelTyCon )
42 import CostCentre       ( mkUserCC )
43 import Id               ( Id, idType, recordSelectorFieldLabel )
44 import PrelInfo         ( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
45 import DataCon          ( DataCon, dataConWrapId, dataConFieldLabels, dataConInstOrigArgTys )
46 import DataCon          ( isExistentialDataCon )
47 import Literal          ( Literal(..) )
48 import TyCon            ( tyConDataCons )
49 import TysWiredIn       ( tupleCon, listTyCon, charDataCon, intDataCon )
50 import BasicTypes       ( RecFlag(..), Boxity(..), ipNameName )
51 import Maybes           ( maybeToBool )
52 import PrelNames        ( hasKey, ratioTyConKey, toPName )
53 import Util             ( zipEqual, zipWithEqual )
54 import Outputable
55
56 import Ratio            ( numerator, denominator )
57 \end{code}
58
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection{dsLet}
63 %*                                                                      *
64 %************************************************************************
65
66 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
67 and transforming it into one for the let-bindings enclosing the body.
68
69 This may seem a bit odd, but (source) let bindings can contain unboxed
70 binds like
71 \begin{verbatim}
72         C x# = e
73 \end{verbatim}
74 This must be transformed to a case expression and, if the type has
75 more than one constructor, may fail.
76
77 \begin{code}
78 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
79
80 dsLet EmptyBinds body
81   = returnDs body
82
83 dsLet (ThenBinds b1 b2) body
84   = dsLet b2 body       `thenDs` \ body' ->
85     dsLet b1 body'
86   
87 -- Special case for bindings which bind unlifted variables
88 -- We need to do a case right away, rather than building
89 -- a tuple and doing selections.
90 -- Silently ignore INLINE pragmas...
91 dsLet bind@(MonoBind (AbsBinds [] [] exports inlines binds) sigs is_rec) body
92   | or [isUnLiftedType (idType g) | (_, g, l) <- exports]
93   = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
94         -- Unlifted bindings are always non-recursive
95         -- and are always a Fun or Pat monobind
96         --
97         -- ToDo: in some bizarre case it's conceivable that there
98         --       could be dict binds in the 'binds'.  (See the notes
99         --       below.  Then pattern-match would fail.  Urk.)
100     case binds of
101       FunMonoBind fun _ matches loc
102         -> putSrcLocDs loc                      $
103            matchWrapper (FunRhs fun) matches    `thenDs` \ (args, rhs) ->
104            ASSERT( null args )  -- Functions aren't lifted
105            returnDs (bindNonRec fun rhs body_w_exports)
106
107       PatMonoBind pat grhss loc
108         -> putSrcLocDs loc                      $
109            dsGuarded grhss                      `thenDs` \ rhs ->
110            mk_error_app pat                     `thenDs` \ error_expr ->
111            matchSimply rhs PatBindRhs pat body_w_exports error_expr
112
113       other -> pprPanic "dsLet: unlifted" (ppr bind $$ ppr body)
114   where
115     body_w_exports               = foldr bind_export body exports
116     bind_export (tvs, g, l) body = ASSERT( null tvs )
117                                    bindNonRec g (Var l) body
118
119     mk_error_app pat = mkErrorAppDs iRREFUT_PAT_ERROR_ID
120                                     (exprType body)
121                                     (showSDoc (ppr pat))
122
123 -- Ordinary case for bindings
124 dsLet (MonoBind binds sigs is_rec) body
125   = dsMonoBinds NoSccs binds []  `thenDs` \ prs ->
126     returnDs (Let (Rec prs) body)
127         -- Use a Rec regardless of is_rec. 
128         -- Why? Because it allows the MonoBinds to be all
129         -- mixed up, which is what happens in one rare case
130         -- Namely, for an AbsBind with no tyvars and no dicts,
131         --         but which does have dictionary bindings.
132         -- See notes with TcSimplify.inferLoop [NO TYVARS]
133         -- It turned out that wrapping a Rec here was the easiest solution
134         --
135         -- NB The previous case dealt with unlifted bindings, so we
136         --    only have to deal with lifted ones now; so Rec is ok
137 \end{code}      
138
139 %************************************************************************
140 %*                                                                      *
141 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
142 %*                                                                      *
143 %************************************************************************
144
145 \begin{code}
146 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
147
148 dsExpr (HsVar var)  = returnDs (Var var)
149 dsExpr (HsIPVar ip) = returnDs (Var (ipNameName ip))
150 dsExpr (HsLit lit)  = dsLit lit
151 -- HsOverLit has been gotten rid of by the type checker
152
153 dsExpr expr@(HsLam a_Match)
154   = matchWrapper LambdaExpr [a_Match]   `thenDs` \ (binders, matching_code) ->
155     returnDs (mkLams binders matching_code)
156
157 dsExpr expr@(HsApp fun arg)      
158   = dsExpr fun          `thenDs` \ core_fun ->
159     dsExpr arg          `thenDs` \ core_arg ->
160     returnDs (core_fun `App` core_arg)
161 \end{code}
162
163 Operator sections.  At first it looks as if we can convert
164 \begin{verbatim}
165         (expr op)
166 \end{verbatim}
167 to
168 \begin{verbatim}
169         \x -> op expr x
170 \end{verbatim}
171
172 But no!  expr might be a redex, and we can lose laziness badly this
173 way.  Consider
174 \begin{verbatim}
175         map (expr op) xs
176 \end{verbatim}
177 for example.  So we convert instead to
178 \begin{verbatim}
179         let y = expr in \x -> op y x
180 \end{verbatim}
181 If \tr{expr} is actually just a variable, say, then the simplifier
182 will sort it out.
183
184 \begin{code}
185 dsExpr (OpApp e1 op _ e2)
186   = dsExpr op                                           `thenDs` \ core_op ->
187     -- for the type of y, we need the type of op's 2nd argument
188     dsExpr e1                           `thenDs` \ x_core ->
189     dsExpr e2                           `thenDs` \ y_core ->
190     returnDs (mkApps core_op [x_core, y_core])
191     
192 dsExpr (SectionL expr op)
193   = dsExpr op                                           `thenDs` \ core_op ->
194     -- for the type of y, we need the type of op's 2nd argument
195     let
196         (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
197         -- Must look through an implicit-parameter type; 
198         -- newtype impossible; hence Type.splitFunTys
199     in
200     dsExpr expr                         `thenDs` \ x_core ->
201     newSysLocalDs x_ty                  `thenDs` \ x_id ->
202     newSysLocalDs y_ty                  `thenDs` \ y_id ->
203
204     returnDs (bindNonRec x_id x_core $
205               Lam y_id (mkApps core_op [Var x_id, Var y_id]))
206
207 -- dsExpr (SectionR op expr)    -- \ x -> op x expr
208 dsExpr (SectionR op expr)
209   = dsExpr op                   `thenDs` \ core_op ->
210     -- for the type of x, we need the type of op's 2nd argument
211     let
212         (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
213         -- See comment with SectionL
214     in
215     dsExpr expr                         `thenDs` \ y_core ->
216     newSysLocalDs x_ty                  `thenDs` \ x_id ->
217     newSysLocalDs y_ty                  `thenDs` \ y_id ->
218
219     returnDs (bindNonRec y_id y_core $
220               Lam x_id (mkApps core_op [Var x_id, Var y_id]))
221
222 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
223   = mapDs dsExpr args           `thenDs` \ core_args ->
224     dsCCall lbl core_args may_gc is_asm result_ty
225         -- dsCCall does all the unboxification, etc.
226
227 dsExpr (HsSCC cc expr)
228   = dsExpr expr                 `thenDs` \ core_expr ->
229     getModuleDs                 `thenDs` \ mod_name ->
230     returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
231
232 -- special case to handle unboxed tuple patterns.
233
234 dsExpr (HsCase discrim matches src_loc)
235  | all ubx_tuple_match matches
236  =  putSrcLocDs src_loc $
237     dsExpr discrim                      `thenDs` \ core_discrim ->
238     matchWrapper CaseAlt matches        `thenDs` \ ([discrim_var], matching_code) ->
239     case matching_code of
240         Case (Var x) bndr alts | x == discrim_var -> 
241                 returnDs (Case core_discrim bndr alts)
242         _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
243   where
244     ubx_tuple_match (Match [TuplePat ps Unboxed] _ _) = True
245     ubx_tuple_match _ = False
246
247 dsExpr (HsCase discrim matches src_loc)
248   = putSrcLocDs src_loc $
249     dsExpr discrim                      `thenDs` \ core_discrim ->
250     matchWrapper CaseAlt matches        `thenDs` \ ([discrim_var], matching_code) ->
251     returnDs (bindNonRec discrim_var core_discrim matching_code)
252
253 dsExpr (HsLet binds body)
254   = dsExpr body         `thenDs` \ body' ->
255     dsLet binds body'
256
257 dsExpr (HsWith expr binds)
258   = dsExpr expr         `thenDs` \ expr' ->
259     foldlDs dsIPBind expr' binds
260     where
261       dsIPBind body (n, e)
262         = dsExpr e      `thenDs` \ e' ->
263           returnDs (Let (NonRec (ipNameName n) e') body)
264
265 -- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
266 -- because the interpretation of `stmts' depends on what sort of thing it is.
267 --
268 dsExpr (HsDoOut ListComp stmts return_id then_id fail_id result_ty src_loc)
269   =     -- Special case for list comprehensions
270     putSrcLocDs src_loc $
271     dsListComp stmts elt_ty
272   where
273     (_, [elt_ty]) = tcSplitTyConApp result_ty
274
275 dsExpr (HsDoOut DoExpr   stmts return_id then_id fail_id result_ty src_loc)
276   = putSrcLocDs src_loc $
277     dsDo DoExpr stmts return_id then_id fail_id result_ty
278
279 dsExpr (HsDoOut PArrComp stmts return_id then_id fail_id result_ty src_loc)
280   =     -- Special case for array comprehensions
281     putSrcLocDs src_loc $
282     dsPArrComp stmts elt_ty
283   where
284     (_, [elt_ty]) = tcSplitTyConApp result_ty
285
286 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
287   = putSrcLocDs src_loc $
288     dsExpr guard_expr   `thenDs` \ core_guard ->
289     dsExpr then_expr    `thenDs` \ core_then ->
290     dsExpr else_expr    `thenDs` \ core_else ->
291     returnDs (mkIfThenElse core_guard core_then core_else)
292 \end{code}
293
294
295 \noindent
296 \underline{\bf Type lambda and application}
297 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~
298 \begin{code}
299 dsExpr (TyLam tyvars expr)
300   = dsExpr expr `thenDs` \ core_expr ->
301     returnDs (mkLams tyvars core_expr)
302
303 dsExpr (TyApp expr tys)
304   = dsExpr expr         `thenDs` \ core_expr ->
305     returnDs (mkTyApps core_expr tys)
306 \end{code}
307
308
309 \noindent
310 \underline{\bf Various data construction things}
311 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
312 \begin{code}
313 dsExpr (ExplicitList ty xs)
314   = go xs
315   where
316     go []     = returnDs (mkNilExpr ty)
317     go (x:xs) = dsExpr x                                `thenDs` \ core_x ->
318                 go xs                                   `thenDs` \ core_xs ->
319                 returnDs (mkConsExpr ty core_x core_xs)
320
321 -- we create a list from the array elements and convert them into a list using
322 -- `PrelPArr.toP'
323 --
324 -- * the main disadvantage to this scheme is that `toP' traverses the list
325 --   twice: once to determine the length and a second time to put to elements
326 --   into the array; this inefficiency could be avoided by exposing some of
327 --   the innards of `PrelPArr' to the compiler (ie, have a `PrelPArrBase') so
328 --   that we can exploit the fact that we already know the length of the array
329 --   here at compile time
330 --
331 dsExpr (ExplicitPArr ty xs)
332   = dsLookupGlobalValue toPName                         `thenDs` \toP      ->
333     dsExpr (ExplicitList ty xs)                         `thenDs` \coreList ->
334     returnDs (mkApps (Var toP) [Type ty, coreList])
335
336 dsExpr (ExplicitTuple expr_list boxity)
337   = mapDs dsExpr expr_list        `thenDs` \ core_exprs  ->
338     returnDs (mkConApp (tupleCon boxity (length expr_list))
339                        (map (Type .  exprType) core_exprs ++ core_exprs))
340
341 dsExpr (ArithSeqOut expr (From from))
342   = dsExpr expr           `thenDs` \ expr2 ->
343     dsExpr from           `thenDs` \ from2 ->
344     returnDs (App expr2 from2)
345
346 dsExpr (ArithSeqOut expr (FromTo from two))
347   = dsExpr expr           `thenDs` \ expr2 ->
348     dsExpr from           `thenDs` \ from2 ->
349     dsExpr two            `thenDs` \ two2 ->
350     returnDs (mkApps expr2 [from2, two2])
351
352 dsExpr (ArithSeqOut expr (FromThen from thn))
353   = dsExpr expr           `thenDs` \ expr2 ->
354     dsExpr from           `thenDs` \ from2 ->
355     dsExpr thn            `thenDs` \ thn2 ->
356     returnDs (mkApps expr2 [from2, thn2])
357
358 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
359   = dsExpr expr           `thenDs` \ expr2 ->
360     dsExpr from           `thenDs` \ from2 ->
361     dsExpr thn            `thenDs` \ thn2 ->
362     dsExpr two            `thenDs` \ two2 ->
363     returnDs (mkApps expr2 [from2, thn2, two2])
364
365 dsExpr (PArrSeqOut expr (FromTo from two))
366   = dsExpr expr           `thenDs` \ expr2 ->
367     dsExpr from           `thenDs` \ from2 ->
368     dsExpr two            `thenDs` \ two2 ->
369     returnDs (mkApps expr2 [from2, two2])
370
371 dsExpr (PArrSeqOut expr (FromThenTo from thn two))
372   = dsExpr expr           `thenDs` \ expr2 ->
373     dsExpr from           `thenDs` \ from2 ->
374     dsExpr thn            `thenDs` \ thn2 ->
375     dsExpr two            `thenDs` \ two2 ->
376     returnDs (mkApps expr2 [from2, thn2, two2])
377
378 dsExpr (PArrSeqOut expr _)
379   = panic "DsExpr.dsExpr: Infinite parallel array!"
380     -- the parser shouldn't have generated it and the renamer and typechecker
381     -- shouldn't have let it through
382 \end{code}
383
384 \noindent
385 \underline{\bf Record construction and update}
386 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
387 For record construction we do this (assuming T has three arguments)
388 \begin{verbatim}
389         T { op2 = e }
390 ==>
391         let err = /\a -> recConErr a 
392         T (recConErr t1 "M.lhs/230/op1") 
393           e 
394           (recConErr t1 "M.lhs/230/op3")
395 \end{verbatim}
396 @recConErr@ then converts its arugment string into a proper message
397 before printing it as
398 \begin{verbatim}
399         M.lhs, line 230: missing field op1 was evaluated
400 \end{verbatim}
401
402 We also handle @C{}@ as valid construction syntax for an unlabelled
403 constructor @C@, setting all of @C@'s fields to bottom.
404
405 \begin{code}
406 dsExpr (RecordConOut data_con con_expr rbinds)
407   = dsExpr con_expr     `thenDs` \ con_expr' ->
408     let
409         (arg_tys, _) = tcSplitFunTys (exprType con_expr')
410         -- A newtype in the corner should be opaque; 
411         -- hence TcType.tcSplitFunTys
412
413         mk_arg (arg_ty, lbl)
414           = case [rhs | (sel_id,rhs,_) <- rbinds,
415                         lbl == recordSelectorFieldLabel sel_id] of
416               (rhs:rhss) -> ASSERT( null rhss )
417                             dsExpr rhs
418               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
419         unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
420
421         labels = dataConFieldLabels data_con
422     in
423
424     (if null labels
425         then mapDs unlabelled_bottom arg_tys
426         else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
427         `thenDs` \ con_args ->
428
429     returnDs (mkApps con_expr' con_args)
430 \end{code}
431
432 Record update is a little harder. Suppose we have the decl:
433 \begin{verbatim}
434         data T = T1 {op1, op2, op3 :: Int}
435                | T2 {op4, op2 :: Int}
436                | T3
437 \end{verbatim}
438 Then we translate as follows:
439 \begin{verbatim}
440         r { op2 = e }
441 ===>
442         let op2 = e in
443         case r of
444           T1 op1 _ op3 -> T1 op1 op2 op3
445           T2 op4 _     -> T2 op4 op2
446           other        -> recUpdError "M.lhs/230"
447 \end{verbatim}
448 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
449 RHSs, and do not generate a Core constructor application directly, because the constructor
450 might do some argument-evaluation first; and may have to throw away some
451 dictionaries.
452
453 \begin{code}
454 dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty dicts [])
455   = dsExpr record_expr
456
457 dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty dicts rbinds)
458   = getSrcLocDs                 `thenDs` \ src_loc ->
459     dsExpr record_expr          `thenDs` \ record_expr' ->
460
461         -- Desugar the rbinds, and generate let-bindings if
462         -- necessary so that we don't lose sharing
463
464     let
465         in_inst_tys  = tcTyConAppArgs record_in_ty      -- Newtype opaque
466         out_inst_tys = tcTyConAppArgs record_out_ty     -- Newtype opaque
467
468         mk_val_arg field old_arg_id 
469           = case [rhs | (sel_id, rhs, _) <- rbinds, 
470                         field == recordSelectorFieldLabel sel_id] of
471               (rhs:rest) -> ASSERT(null rest) rhs
472               []         -> HsVar old_arg_id
473
474         mk_alt con
475           = newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
476                 -- This call to dataConArgTys won't work for existentials
477             let 
478                 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
479                                         (dataConFieldLabels con) arg_ids
480                 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConWrapId con)) 
481                                                   out_inst_tys)
482                                            dicts)
483                                   val_args
484             in
485             returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
486                                     rhs
487                                     record_out_ty
488                                     src_loc)
489     in
490         -- Record stuff doesn't work for existentials
491     ASSERT( all (not . isExistentialDataCon) data_cons )
492
493         -- It's important to generate the match with matchWrapper,
494         -- and the right hand sides with applications of the wrapper Id
495         -- so that everything works when we are doing fancy unboxing on the
496         -- constructor aguments.
497     mapDs mk_alt cons_to_upd            `thenDs` \ alts ->
498     matchWrapper RecUpd alts            `thenDs` \ ([discrim_var], matching_code) ->
499
500     returnDs (bindNonRec discrim_var record_expr' matching_code)
501
502   where
503     updated_fields :: [FieldLabel]
504     updated_fields = [recordSelectorFieldLabel sel_id | (sel_id,_,_) <- rbinds]
505
506         -- Get the type constructor from the first field label, 
507         -- so that we are sure it'll have all its DataCons
508         -- (In GHCI, it's possible that some TyCons may not have all
509         --  their constructors, in a module-loop situation.)
510     tycon       = fieldLabelTyCon (head updated_fields)
511     data_cons   = tyConDataCons tycon
512     cons_to_upd = filter has_all_fields data_cons
513
514     has_all_fields :: DataCon -> Bool
515     has_all_fields con_id 
516       = all (`elem` con_fields) updated_fields
517       where
518         con_fields = dataConFieldLabels con_id
519 \end{code}
520
521
522 \noindent
523 \underline{\bf Dictionary lambda and application}
524 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
525 @DictLam@ and @DictApp@ turn into the regular old things.
526 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
527 complicated; reminiscent of fully-applied constructors.
528 \begin{code}
529 dsExpr (DictLam dictvars expr)
530   = dsExpr expr `thenDs` \ core_expr ->
531     returnDs (mkLams dictvars core_expr)
532
533 ------------------
534
535 dsExpr (DictApp expr dicts)     -- becomes a curried application
536   = dsExpr expr                 `thenDs` \ core_expr ->
537     returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
538 \end{code}
539
540 \begin{code}
541
542 #ifdef DEBUG
543 -- HsSyn constructs that just shouldn't be here:
544 dsExpr (HsDo _ _ _)         = panic "dsExpr:HsDo"
545 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
546 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
547 dsExpr (PArrSeqIn _)        = panic "dsExpr:PArrSeqIn"
548 #endif
549
550 \end{code}
551
552 %--------------------------------------------------------------------
553
554 Basically does the translation given in the Haskell~1.3 report:
555
556 \begin{code}
557 dsDo    :: HsDoContext
558         -> [TypecheckedStmt]
559         -> Id           -- id for: return m
560         -> Id           -- id for: (>>=) m
561         -> Id           -- id for: fail m
562         -> Type         -- Element type; the whole expression has type (m t)
563         -> DsM CoreExpr
564
565 dsDo do_or_lc stmts return_id then_id fail_id result_ty
566   = let
567         (_, b_ty) = tcSplitAppTy result_ty      -- result_ty must be of the form (m b)
568         is_do     = case do_or_lc of
569                         DoExpr   -> True
570                         _        -> False
571         
572         -- For ExprStmt, see the comments near HsExpr.Stmt about 
573         -- exactly what ExprStmts mean!
574         --
575         -- In dsDo we can only see DoStmt and ListComp (no gaurds)
576
577         go [ResultStmt expr locn]
578           | is_do     = do_expr expr locn
579           | otherwise = do_expr expr locn       `thenDs` \ expr2 ->
580                         returnDs (mkApps (Var return_id) [Type b_ty, expr2])
581
582         go (ExprStmt expr a_ty locn : stmts)
583           | is_do       -- Do expression
584           = do_expr expr locn           `thenDs` \ expr2 ->
585             go stmts                    `thenDs` \ rest  ->
586             newSysLocalDs a_ty          `thenDs` \ ignored_result_id ->
587             returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2, 
588                                             Lam ignored_result_id rest])
589
590            | otherwise  -- List comprehension
591           = do_expr expr locn                   `thenDs` \ expr2 ->
592             go stmts                            `thenDs` \ rest ->
593             let
594                 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
595             in
596             mkStringLit msg                     `thenDs` \ core_msg ->
597             returnDs (mkIfThenElse expr2 rest 
598                                    (App (App (Var fail_id) (Type b_ty)) core_msg))
599     
600         go (LetStmt binds : stmts )
601           = go stmts            `thenDs` \ rest   ->
602             dsLet binds rest
603             
604         go (BindStmt pat expr locn : stmts)
605           = putSrcLocDs locn $
606             dsExpr expr            `thenDs` \ expr2 ->
607             let
608                 a_ty       = outPatType pat
609                 fail_expr  = HsApp (TyApp (HsVar fail_id) [b_ty])
610                                    (HsLit (HsString (_PK_ msg)))
611                 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
612                 main_match = mkSimpleMatch [pat] 
613                                            (HsDoOut do_or_lc stmts return_id then_id
614                                                     fail_id result_ty locn)
615                                            result_ty locn
616                 the_matches
617                   | failureFreePat pat = [main_match]
618                   | otherwise          =
619                       [ main_match
620                       , mkSimpleMatch [WildPat a_ty] fail_expr result_ty locn
621                       ]
622             in
623             matchWrapper (DoCtxt do_or_lc) the_matches  `thenDs` \ (binders, matching_code) ->
624             returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
625                                             mkLams binders matching_code])
626     in
627     go stmts
628
629   where
630     do_expr expr locn = putSrcLocDs locn (dsExpr expr)
631 \end{code}
632
633
634 %************************************************************************
635 %*                                                                      *
636 \subsection[DsExpr-literals]{Literals}
637 %*                                                                      *
638 %************************************************************************
639
640 We give int/float literals type @Integer@ and @Rational@, respectively.
641 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
642 around them.
643
644 ToDo: put in range checks for when converting ``@i@''
645 (or should that be in the typechecker?)
646
647 For numeric literals, we try to detect there use at a standard type
648 (@Int@, @Float@, etc.) are directly put in the right constructor.
649 [NB: down with the @App@ conversion.]
650
651 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
652
653 \begin{code}
654 dsLit :: HsLit -> DsM CoreExpr
655 dsLit (HsChar c)       = returnDs (mkConApp charDataCon [mkLit (MachChar c)])
656 dsLit (HsCharPrim c)   = returnDs (mkLit (MachChar c))
657 dsLit (HsString str)   = mkStringLitFS str
658 dsLit (HsStringPrim s) = returnDs (mkLit (MachStr s))
659 dsLit (HsInteger i)    = mkIntegerLit i
660 dsLit (HsInt i)        = returnDs (mkConApp intDataCon [mkIntLit i])
661 dsLit (HsIntPrim i)    = returnDs (mkIntLit i)
662 dsLit (HsFloatPrim f)  = returnDs (mkLit (MachFloat f))
663 dsLit (HsDoublePrim d) = returnDs (mkLit (MachDouble d))
664 dsLit (HsLitLit str ty)
665   = ASSERT( maybeToBool maybe_ty )
666     returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
667   where
668     (maybe_ty, wrap_fn) = resultWrapper ty
669     Just rep_ty         = maybe_ty
670
671 dsLit (HsRat r ty)
672   = mkIntegerLit (numerator r)          `thenDs` \ num ->
673     mkIntegerLit (denominator r)        `thenDs` \ denom ->
674     returnDs (mkConApp ratio_data_con [Type integer_ty, num, denom])
675   where
676     (ratio_data_con, integer_ty) 
677         = case tcSplitTyConApp ty of
678                 (tycon, [i_ty]) -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)
679                                    (head (tyConDataCons tycon), i_ty)
680 \end{code}