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