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