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