[project @ 2001-11-30 09:39:32 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(..), 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 )
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 )
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 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
266   | maybeToBool maybe_list_comp
267   =     -- Special case for list comprehensions
268     putSrcLocDs src_loc $
269     dsListComp stmts elt_ty
270
271   | otherwise
272   = putSrcLocDs src_loc $
273     dsDo do_or_lc stmts return_id then_id fail_id result_ty
274   where
275     maybe_list_comp 
276         = case (do_or_lc, tcSplitTyConApp_maybe result_ty) of
277             (ListComp, Just (tycon, [elt_ty]))
278                   | tycon == listTyCon
279                  -> Just elt_ty
280             other -> Nothing
281         -- We need the ListComp form to use deListComp (rather than the "do" form)
282         -- because the interpretation of ExprStmt depends on what sort of thing
283         -- it is.
284
285     Just elt_ty = maybe_list_comp
286
287 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
288   = putSrcLocDs src_loc $
289     dsExpr guard_expr   `thenDs` \ core_guard ->
290     dsExpr then_expr    `thenDs` \ core_then ->
291     dsExpr else_expr    `thenDs` \ core_else ->
292     returnDs (mkIfThenElse core_guard core_then core_else)
293 \end{code}
294
295
296 \noindent
297 \underline{\bf Type lambda and application}
298 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~
299 \begin{code}
300 dsExpr (TyLam tyvars expr)
301   = dsExpr expr `thenDs` \ core_expr ->
302     returnDs (mkLams tyvars core_expr)
303
304 dsExpr (TyApp expr tys)
305   = dsExpr expr         `thenDs` \ core_expr ->
306     returnDs (mkTyApps core_expr tys)
307 \end{code}
308
309
310 \noindent
311 \underline{\bf Various data construction things}
312 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
313 \begin{code}
314 dsExpr (ExplicitList ty xs)
315   = go xs
316   where
317     go []     = returnDs (mkNilExpr ty)
318     go (x:xs) = dsExpr x                                `thenDs` \ core_x ->
319                 go xs                                   `thenDs` \ core_xs ->
320                 returnDs (mkConsExpr ty core_x core_xs)
321
322 dsExpr (ExplicitTuple expr_list boxity)
323   = mapDs dsExpr expr_list        `thenDs` \ core_exprs  ->
324     returnDs (mkConApp (tupleCon boxity (length expr_list))
325                        (map (Type .  exprType) core_exprs ++ core_exprs))
326
327 dsExpr (ArithSeqOut expr (From from))
328   = dsExpr expr           `thenDs` \ expr2 ->
329     dsExpr from           `thenDs` \ from2 ->
330     returnDs (App expr2 from2)
331
332 dsExpr (ArithSeqOut expr (FromTo from two))
333   = dsExpr expr           `thenDs` \ expr2 ->
334     dsExpr from           `thenDs` \ from2 ->
335     dsExpr two            `thenDs` \ two2 ->
336     returnDs (mkApps expr2 [from2, two2])
337
338 dsExpr (ArithSeqOut expr (FromThen from thn))
339   = dsExpr expr           `thenDs` \ expr2 ->
340     dsExpr from           `thenDs` \ from2 ->
341     dsExpr thn            `thenDs` \ thn2 ->
342     returnDs (mkApps expr2 [from2, thn2])
343
344 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
345   = dsExpr expr           `thenDs` \ expr2 ->
346     dsExpr from           `thenDs` \ from2 ->
347     dsExpr thn            `thenDs` \ thn2 ->
348     dsExpr two            `thenDs` \ two2 ->
349     returnDs (mkApps expr2 [from2, thn2, two2])
350 \end{code}
351
352 \noindent
353 \underline{\bf Record construction and update}
354 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
355 For record construction we do this (assuming T has three arguments)
356 \begin{verbatim}
357         T { op2 = e }
358 ==>
359         let err = /\a -> recConErr a 
360         T (recConErr t1 "M.lhs/230/op1") 
361           e 
362           (recConErr t1 "M.lhs/230/op3")
363 \end{verbatim}
364 @recConErr@ then converts its arugment string into a proper message
365 before printing it as
366 \begin{verbatim}
367         M.lhs, line 230: missing field op1 was evaluated
368 \end{verbatim}
369
370 We also handle @C{}@ as valid construction syntax for an unlabelled
371 constructor @C@, setting all of @C@'s fields to bottom.
372
373 \begin{code}
374 dsExpr (RecordConOut data_con con_expr rbinds)
375   = dsExpr con_expr     `thenDs` \ con_expr' ->
376     let
377         (arg_tys, _) = tcSplitFunTys (exprType con_expr')
378         -- A newtype in the corner should be opaque; 
379         -- hence TcType.tcSplitFunTys
380
381         mk_arg (arg_ty, lbl)
382           = case [rhs | (sel_id,rhs,_) <- rbinds,
383                         lbl == recordSelectorFieldLabel sel_id] of
384               (rhs:rhss) -> ASSERT( null rhss )
385                             dsExpr rhs
386               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
387         unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
388
389         labels = dataConFieldLabels data_con
390     in
391
392     (if null labels
393         then mapDs unlabelled_bottom arg_tys
394         else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
395         `thenDs` \ con_args ->
396
397     returnDs (mkApps con_expr' con_args)
398 \end{code}
399
400 Record update is a little harder. Suppose we have the decl:
401 \begin{verbatim}
402         data T = T1 {op1, op2, op3 :: Int}
403                | T2 {op4, op2 :: Int}
404                | T3
405 \end{verbatim}
406 Then we translate as follows:
407 \begin{verbatim}
408         r { op2 = e }
409 ===>
410         let op2 = e in
411         case r of
412           T1 op1 _ op3 -> T1 op1 op2 op3
413           T2 op4 _     -> T2 op4 op2
414           other        -> recUpdError "M.lhs/230"
415 \end{verbatim}
416 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
417 RHSs, and do not generate a Core constructor application directly, because the constructor
418 might do some argument-evaluation first; and may have to throw away some
419 dictionaries.
420
421 \begin{code}
422 dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty dicts [])
423   = dsExpr record_expr
424
425 dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty dicts rbinds)
426   = getSrcLocDs                 `thenDs` \ src_loc ->
427     dsExpr record_expr          `thenDs` \ record_expr' ->
428
429         -- Desugar the rbinds, and generate let-bindings if
430         -- necessary so that we don't lose sharing
431
432     let
433         in_inst_tys  = tcTyConAppArgs record_in_ty      -- Newtype opaque
434         out_inst_tys = tcTyConAppArgs record_out_ty     -- Newtype opaque
435
436         mk_val_arg field old_arg_id 
437           = case [rhs | (sel_id, rhs, _) <- rbinds, 
438                         field == recordSelectorFieldLabel sel_id] of
439               (rhs:rest) -> ASSERT(null rest) rhs
440               []         -> HsVar old_arg_id
441
442         mk_alt con
443           = newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
444                 -- This call to dataConArgTys won't work for existentials
445             let 
446                 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
447                                         (dataConFieldLabels con) arg_ids
448                 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConWrapId con)) 
449                                                   out_inst_tys)
450                                            dicts)
451                                   val_args
452             in
453             returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
454                                     rhs
455                                     record_out_ty
456                                     src_loc)
457     in
458         -- Record stuff doesn't work for existentials
459     ASSERT( all (not . isExistentialDataCon) data_cons )
460
461         -- It's important to generate the match with matchWrapper,
462         -- and the right hand sides with applications of the wrapper Id
463         -- so that everything works when we are doing fancy unboxing on the
464         -- constructor aguments.
465     mapDs mk_alt cons_to_upd            `thenDs` \ alts ->
466     matchWrapper RecUpd alts            `thenDs` \ ([discrim_var], matching_code) ->
467
468     returnDs (bindNonRec discrim_var record_expr' matching_code)
469
470   where
471     updated_fields :: [FieldLabel]
472     updated_fields = [recordSelectorFieldLabel sel_id | (sel_id,_,_) <- rbinds]
473
474         -- Get the type constructor from the first field label, 
475         -- so that we are sure it'll have all its DataCons
476         -- (In GHCI, it's possible that some TyCons may not have all
477         --  their constructors, in a module-loop situation.)
478     tycon       = fieldLabelTyCon (head updated_fields)
479     data_cons   = tyConDataCons tycon
480     cons_to_upd = filter has_all_fields data_cons
481
482     has_all_fields :: DataCon -> Bool
483     has_all_fields con_id 
484       = all (`elem` con_fields) updated_fields
485       where
486         con_fields = dataConFieldLabels con_id
487 \end{code}
488
489
490 \noindent
491 \underline{\bf Dictionary lambda and application}
492 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
493 @DictLam@ and @DictApp@ turn into the regular old things.
494 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
495 complicated; reminiscent of fully-applied constructors.
496 \begin{code}
497 dsExpr (DictLam dictvars expr)
498   = dsExpr expr `thenDs` \ core_expr ->
499     returnDs (mkLams dictvars core_expr)
500
501 ------------------
502
503 dsExpr (DictApp expr dicts)     -- becomes a curried application
504   = dsExpr expr                 `thenDs` \ core_expr ->
505     returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
506 \end{code}
507
508 \begin{code}
509
510 #ifdef DEBUG
511 -- HsSyn constructs that just shouldn't be here:
512 dsExpr (HsDo _ _ _)         = panic "dsExpr:HsDo"
513 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
514 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
515 #endif
516
517 \end{code}
518
519 %--------------------------------------------------------------------
520
521 Basically does the translation given in the Haskell~1.3 report:
522
523 \begin{code}
524 dsDo    :: HsDoContext
525         -> [TypecheckedStmt]
526         -> Id           -- id for: return m
527         -> Id           -- id for: (>>=) m
528         -> Id           -- id for: fail m
529         -> Type         -- Element type; the whole expression has type (m t)
530         -> DsM CoreExpr
531
532 dsDo do_or_lc stmts return_id then_id fail_id result_ty
533   = let
534         (_, b_ty) = tcSplitAppTy result_ty      -- result_ty must be of the form (m b)
535         is_do     = case do_or_lc of
536                         DoExpr   -> True
537                         ListComp -> False
538         
539         -- For ExprStmt, see the comments near HsExpr.Stmt about 
540         -- exactly what ExprStmts mean!
541         --
542         -- In dsDo we can only see DoStmt and ListComp (no gaurds)
543
544         go [ResultStmt expr locn]
545           | is_do     = do_expr expr locn
546           | otherwise = do_expr expr locn       `thenDs` \ expr2 ->
547                         returnDs (mkApps (Var return_id) [Type b_ty, expr2])
548
549         go (ExprStmt expr a_ty locn : stmts)
550           | is_do       -- Do expression
551           = do_expr expr locn           `thenDs` \ expr2 ->
552             go stmts                    `thenDs` \ rest  ->
553             newSysLocalDs a_ty          `thenDs` \ ignored_result_id ->
554             returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2, 
555                                             Lam ignored_result_id rest])
556
557            | otherwise  -- List comprehension
558           = do_expr expr locn                   `thenDs` \ expr2 ->
559             go stmts                            `thenDs` \ rest ->
560             let
561                 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
562             in
563             mkStringLit msg                     `thenDs` \ core_msg ->
564             returnDs (mkIfThenElse expr2 rest 
565                                    (App (App (Var fail_id) (Type b_ty)) core_msg))
566     
567         go (LetStmt binds : stmts )
568           = go stmts            `thenDs` \ rest   ->
569             dsLet binds rest
570             
571         go (BindStmt pat expr locn : stmts)
572           = putSrcLocDs locn $
573             dsExpr expr            `thenDs` \ expr2 ->
574             let
575                 a_ty       = outPatType pat
576                 fail_expr  = HsApp (TyApp (HsVar fail_id) [b_ty])
577                                    (HsLit (HsString (_PK_ msg)))
578                 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
579                 main_match = mkSimpleMatch [pat] 
580                                            (HsDoOut do_or_lc stmts return_id then_id
581                                                     fail_id result_ty locn)
582                                            result_ty locn
583                 the_matches
584                   | failureFreePat pat = [main_match]
585                   | otherwise          =
586                       [ main_match
587                       , mkSimpleMatch [WildPat a_ty] fail_expr result_ty locn
588                       ]
589             in
590             matchWrapper (DoCtxt do_or_lc) the_matches  `thenDs` \ (binders, matching_code) ->
591             returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
592                                             mkLams binders matching_code])
593     in
594     go stmts
595
596   where
597     do_expr expr locn = putSrcLocDs locn (dsExpr expr)
598 \end{code}
599
600
601 %************************************************************************
602 %*                                                                      *
603 \subsection[DsExpr-literals]{Literals}
604 %*                                                                      *
605 %************************************************************************
606
607 We give int/float literals type @Integer@ and @Rational@, respectively.
608 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
609 around them.
610
611 ToDo: put in range checks for when converting ``@i@''
612 (or should that be in the typechecker?)
613
614 For numeric literals, we try to detect there use at a standard type
615 (@Int@, @Float@, etc.) are directly put in the right constructor.
616 [NB: down with the @App@ conversion.]
617
618 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
619
620 \begin{code}
621 dsLit :: HsLit -> DsM CoreExpr
622 dsLit (HsChar c)       = returnDs (mkConApp charDataCon [mkLit (MachChar c)])
623 dsLit (HsCharPrim c)   = returnDs (mkLit (MachChar c))
624 dsLit (HsString str)   = mkStringLitFS str
625 dsLit (HsStringPrim s) = returnDs (mkLit (MachStr s))
626 dsLit (HsInteger i)    = mkIntegerLit i
627 dsLit (HsInt i)        = returnDs (mkConApp intDataCon [mkIntLit i])
628 dsLit (HsIntPrim i)    = returnDs (mkIntLit i)
629 dsLit (HsFloatPrim f)  = returnDs (mkLit (MachFloat f))
630 dsLit (HsDoublePrim d) = returnDs (mkLit (MachDouble d))
631 dsLit (HsLitLit str ty)
632   = ASSERT( maybeToBool maybe_ty )
633     returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
634   where
635     (maybe_ty, wrap_fn) = resultWrapper ty
636     Just rep_ty         = maybe_ty
637
638 dsLit (HsRat r ty)
639   = mkIntegerLit (numerator r)          `thenDs` \ num ->
640     mkIntegerLit (denominator r)        `thenDs` \ denom ->
641     returnDs (mkConApp ratio_data_con [Type integer_ty, num, denom])
642   where
643     (ratio_data_con, integer_ty) 
644         = case tcSplitTyConApp ty of
645                 (tycon, [i_ty]) -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)
646                                    (head (tyConDataCons tycon), i_ty)
647 \end{code}