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