[project @ 2000-11-15 17:07:17 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(..), StmtCtxt(..), Match(..), HsBinds(..), MonoBinds(..), 
15                           mkSimpleMatch
16                         )
17 import TcHsSyn          ( TypecheckedHsExpr, TypecheckedHsBinds,
18                           TypecheckedStmt
19                         )
20 import CoreSyn
21 import CoreUtils        ( exprType, mkIfThenElse, bindNonRec )
22
23 import DsMonad
24 import DsBinds          ( dsMonoBinds, AutoScc(..) )
25 import DsGRHSs          ( dsGuarded )
26 import DsCCall          ( dsCCall, resultWrapper )
27 import DsListComp       ( dsListComp )
28 import DsUtils          ( mkErrorAppDs, mkDsLets, mkStringLit, mkStringLitFS, 
29                           mkConsExpr, mkNilExpr, mkIntegerLit
30                         )
31 import Match            ( matchWrapper, matchSimply )
32
33 import FieldLabel       ( FieldLabel, fieldLabelTyCon )
34 import CostCentre       ( mkUserCC )
35 import Id               ( Id, idType, recordSelectorFieldLabel )
36 import PrelInfo         ( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
37 import DataCon          ( DataCon, dataConWrapId, dataConArgTys, dataConFieldLabels )
38 import DataCon          ( isExistentialDataCon )
39 import Literal          ( Literal(..) )
40 import TyCon            ( tyConDataCons )
41 import Type             ( splitFunTys,
42                           splitAlgTyConApp, splitTyConApp_maybe, tyConAppArgs,
43                           splitAppTy, isUnLiftedType, Type
44                         )
45 import TysWiredIn       ( tupleCon, listTyCon, charDataCon, intDataCon, isIntegerTy )
46 import BasicTypes       ( RecFlag(..), Boxity(..) )
47 import Maybes           ( maybeToBool )
48 import PrelNames        ( hasKey, ratioTyConKey )
49 import Util             ( zipEqual, zipWithEqual )
50 import Outputable
51
52 import Ratio            ( numerator, denominator )
53 \end{code}
54
55
56 %************************************************************************
57 %*                                                                      *
58 \subsection{dsLet}
59 %*                                                                      *
60 %************************************************************************
61
62 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
63 and transforming it into one for the let-bindings enclosing the body.
64
65 This may seem a bit odd, but (source) let bindings can contain unboxed
66 binds like
67 \begin{verbatim}
68         C x# = e
69 \end{verbatim}
70 This must be transformed to a case expression and, if the type has
71 more than one constructor, may fail.
72
73 \begin{code}
74 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
75
76 dsLet EmptyBinds body
77   = returnDs body
78
79 dsLet (ThenBinds b1 b2) body
80   = dsLet b2 body       `thenDs` \ body' ->
81     dsLet b1 body'
82   
83 -- Special case for bindings which bind unlifted variables
84 -- Silently ignore INLINE pragmas...
85 dsLet (MonoBind (AbsBinds [] [] binder_triples inlines
86                           (PatMonoBind pat grhss loc)) sigs is_rec) body
87   | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
88   = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
89     putSrcLocDs loc                     $
90     dsGuarded grhss                     `thenDs` \ rhs ->
91     let
92         body' = foldr bind body binder_triples
93         bind (tyvars, g, l) body = ASSERT( null tyvars )
94                                    bindNonRec g (Var l) body
95     in
96     mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat))
97     `thenDs` \ error_expr ->
98     matchSimply rhs PatBindMatch pat body' error_expr
99   where
100     result_ty = exprType body
101
102 -- Ordinary case for bindings
103 dsLet (MonoBind binds sigs is_rec) body
104   = dsMonoBinds NoSccs binds []  `thenDs` \ prs ->
105     case is_rec of
106       Recursive    -> returnDs (Let (Rec prs) body)
107       NonRecursive -> returnDs (mkDsLets [NonRec b r | (b,r) <- prs] body)
108 \end{code}
109
110 %************************************************************************
111 %*                                                                      *
112 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
113 %*                                                                      *
114 %************************************************************************
115
116 \begin{code}
117 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
118
119 dsExpr (HsVar var)       = returnDs (Var var)
120 dsExpr (HsIPVar var)     = returnDs (Var var)
121 dsExpr (HsLit lit)       = dsLit lit
122 -- HsOverLit has been gotten rid of by the type checker
123
124 dsExpr expr@(HsLam a_Match)
125   = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
126     returnDs (mkLams binders matching_code)
127
128 dsExpr expr@(HsApp fun arg)      
129   = dsExpr fun          `thenDs` \ core_fun ->
130     dsExpr arg          `thenDs` \ core_arg ->
131     returnDs (core_fun `App` core_arg)
132
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 CaseMatch matches "case" `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 CaseMatch matches "case" `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 "return" in a do block is a call to "PrelBase.return", and
252         -- not a ReturnStmt.  Only the ListComp form has ReturnStmts
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 (dataConArgTys 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 RecUpdMatch alts "record update"       `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    :: StmtCtxt
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         
505         go [ReturnStmt expr] 
506           = dsExpr expr                 `thenDs` \ expr2 ->
507             returnDs (mkApps (Var return_id) [Type b_ty, expr2])
508     
509         go (GuardStmt expr locn : stmts)
510           = do_expr expr locn                   `thenDs` \ expr2 ->
511             go stmts                            `thenDs` \ rest ->
512             let msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
513             in
514             mkStringLit msg                     `thenDs` \ core_msg ->
515             returnDs (mkIfThenElse expr2 
516                                    rest 
517                                    (App (App (Var fail_id) 
518                                              (Type b_ty))
519                                              core_msg))
520     
521         go (ExprStmt expr locn : stmts)
522           = do_expr expr locn           `thenDs` \ expr2 ->
523             let
524                 (_, a_ty) = splitAppTy (exprType expr2)  -- Must be of form (m a)
525             in
526             if null stmts then
527                 returnDs expr2
528             else
529                 go stmts                `thenDs` \ rest  ->
530                 newSysLocalDs a_ty              `thenDs` \ ignored_result_id ->
531                 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2, 
532                                                 Lam ignored_result_id rest])
533     
534         go (LetStmt binds : stmts )
535           = go stmts            `thenDs` \ rest   ->
536             dsLet binds rest
537             
538         go (BindStmt pat expr locn : stmts)
539           = putSrcLocDs locn $
540             dsExpr expr            `thenDs` \ expr2 ->
541             let
542                 (_, a_ty)  = splitAppTy (exprType expr2) -- Must be of form (m a)
543                 fail_expr  = HsApp (TyApp (HsVar fail_id) [b_ty])
544                                    (HsLit (HsString (_PK_ msg)))
545                 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
546                 main_match = mkSimpleMatch [pat] 
547                                            (HsDoOut do_or_lc stmts return_id then_id
548                                                     fail_id result_ty locn)
549                                            (Just result_ty) locn
550                 the_matches
551                   | failureFreePat pat = [main_match]
552                   | otherwise          =
553                       [ main_match
554                       , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
555                       ]
556             in
557             matchWrapper DoBindMatch the_matches match_msg
558                                 `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
567     match_msg = case do_or_lc of
568                         DoStmt   -> "`do' statement"
569                         ListComp -> "comprehension"
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