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