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