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