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