2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[DsExpr]{Matching expressions (Exprs)}
7 module DsExpr ( dsExpr ) where
9 #include "HsVersions.h"
11 import {-# SOURCE #-} DsBinds (dsBinds )
13 import HsSyn ( failureFreePat,
14 HsExpr(..), OutPat(..), HsLit(..), ArithSeqInfo(..),
15 Stmt(..), DoOrListComp(..), Match(..), HsBinds, HsType, Fixity,
18 import TcHsSyn ( TypecheckedHsExpr, TypecheckedHsBinds,
19 TypecheckedRecordBinds, TypecheckedPat,
27 import DsCCall ( dsCCall )
28 import DsListComp ( dsListComp )
29 import DsUtils ( mkAppDs, mkConDs, dsExprToAtomGivenTy,
30 mkErrorAppDs, showForErr, DsCoreArg
32 import Match ( matchWrapper )
34 import CoreUtils ( coreExprType, mkCoreIfThenElse )
35 import CostCentre ( mkUserCC )
36 import FieldLabel ( FieldLabel )
37 import Id ( dataConTyCon, dataConArgTys, dataConFieldLabels,
38 recordSelectorFieldLabel, Id
40 import Literal ( mkMachInt, Literal(..) )
41 import Name ( Name{--O only-} )
42 import PrelVals ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID )
43 import TyCon ( isNewTyCon )
44 import Type ( splitFunTys, typePrimRep, mkTyConApp,
45 splitAlgTyConApp, splitTyConApp_maybe,
48 import TysWiredIn ( tupleCon, nilDataCon, consDataCon, listTyCon, mkListTy,
51 import TyVar ( GenTyVar{-instance Eq-} )
52 import Maybes ( maybeToBool )
53 import Util ( zipEqual )
56 mk_nil_con ty = mkCon nilDataCon [ty] [] -- micro utility...
59 The funny business to do with variables is that we look them up in the
60 Id-to-Id and Id-to-Id maps that the monadery is carrying
61 around; if we get hits, we use the value accordingly.
63 %************************************************************************
65 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
67 %************************************************************************
70 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
72 dsExpr e@(HsVar var) = dsId var
75 %************************************************************************
77 \subsection[DsExpr-literals]{Literals}
79 %************************************************************************
81 We give int/float literals type Integer and Rational, respectively.
82 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
85 ToDo: put in range checks for when converting "i"
86 (or should that be in the typechecker?)
88 For numeric literals, we try to detect there use at a standard type
89 (Int, Float, etc.) are directly put in the right constructor.
90 [NB: down with the @App@ conversion.]
91 Otherwise, we punt, putting in a "NoRep" Core literal (where the
92 representation decisions are delayed)...
94 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
97 dsExpr (HsLitOut (HsString s) _)
99 = returnDs (mk_nil_con charTy)
103 the_char = mkCon charDataCon [] [LitArg (MachChar (_HEAD_ s))]
104 the_nil = mk_nil_con charTy
106 mkConDs consDataCon [TyArg charTy, VarArg the_char, VarArg the_nil]
108 -- "_" => build (\ c n -> c 'c' n) -- LATER
110 -- "str" ==> build (\ c n -> foldr charTy T c n "str")
113 dsExpr (HsLitOut (HsString str) _)
114 = newTyVarsDs [alphaTyVar] `thenDs` \ [new_tyvar] ->
116 new_ty = mkTyVarTy new_tyvar
119 charTy `mkFunTy` (new_ty `mkFunTy` new_ty),
121 mkForallTy [alphaTyVar]
122 ((charTy `mkFunTy` (alphaTy `mkFunTy` alphaTy))
123 `mkFunTy` (alphaTy `mkFunTy` alphaTy))
124 ] `thenDs` \ [c,n,g] ->
125 returnDs (mkBuild charTy new_tyvar c n g (
127 (CoTyApp (CoTyApp (Var foldrId) charTy) new_ty) *** ensure non-prim type ***
128 [VarArg c,VarArg n,LitArg (NoRepStr str)]))
131 -- otherwise, leave it as a NoRepStr;
132 -- the Core-to-STG pass will wrap it in an application of "unpackCStringId".
134 dsExpr (HsLitOut (HsString str) _)
135 = returnDs (Lit (NoRepStr str))
137 dsExpr (HsLitOut (HsLitLit s) ty)
138 = returnDs ( mkCon data_con [] [LitArg (MachLitLit s kind)] )
141 = case (maybeBoxedPrimType ty) of
142 Just (boxing_data_con, prim_ty)
143 -> (boxing_data_con, typePrimRep prim_ty)
145 -> pprPanic "ERROR: ``literal-literal'' not a single-constructor type: "
146 (hcat [ptext s, text "; type: ", ppr ty])
148 dsExpr (HsLitOut (HsInt i) ty)
149 = returnDs (Lit (NoRepInteger i ty))
151 dsExpr (HsLitOut (HsFrac r) ty)
152 = returnDs (Lit (NoRepRational r ty))
154 -- others where we know what to do:
156 dsExpr (HsLitOut (HsIntPrim i) _)
157 = if (i >= toInteger minInt && i <= toInteger maxInt) then
158 returnDs (Lit (mkMachInt i))
160 error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
162 dsExpr (HsLitOut (HsFloatPrim f) _)
163 = returnDs (Lit (MachFloat f))
164 -- ToDo: range checking needed!
166 dsExpr (HsLitOut (HsDoublePrim d) _)
167 = returnDs (Lit (MachDouble d))
168 -- ToDo: range checking needed!
170 dsExpr (HsLitOut (HsChar c) _)
171 = returnDs ( mkCon charDataCon [] [LitArg (MachChar c)] )
173 dsExpr (HsLitOut (HsCharPrim c) _)
174 = returnDs (Lit (MachChar c))
176 dsExpr (HsLitOut (HsStringPrim s) _)
177 = returnDs (Lit (MachStr s))
179 -- end of literals magic. --
181 dsExpr expr@(HsLam a_Match)
182 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
183 returnDs ( mkValLam binders matching_code )
185 dsExpr expr@(HsApp fun arg)
186 = dsExpr fun `thenDs` \ core_fun ->
187 dsExpr arg `thenDs` \ core_arg ->
188 dsExprToAtomGivenTy core_arg (coreExprType core_arg) $ \ atom_arg ->
189 returnDs (core_fun `App` atom_arg)
193 Operator sections. At first it looks as if we can convert
202 But no! expr might be a redex, and we can lose laziness badly this
207 for example. So we convert instead to
209 let y = expr in \x -> op y x
211 If \tr{expr} is actually just a variable, say, then the simplifier
215 dsExpr (OpApp e1 op _ e2)
216 = dsExpr op `thenDs` \ core_op ->
217 -- for the type of y, we need the type of op's 2nd argument
219 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
221 dsExpr e1 `thenDs` \ x_core ->
222 dsExpr e2 `thenDs` \ y_core ->
223 dsExprToAtomGivenTy x_core x_ty $ \ x_atom ->
224 dsExprToAtomGivenTy y_core y_ty $ \ y_atom ->
225 returnDs (core_op `App` x_atom `App` y_atom)
227 dsExpr (SectionL expr op)
228 = dsExpr op `thenDs` \ core_op ->
229 -- for the type of y, we need the type of op's 2nd argument
231 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
233 dsExpr expr `thenDs` \ x_core ->
234 dsExprToAtomGivenTy x_core x_ty $ \ x_atom ->
236 newSysLocalDs y_ty `thenDs` \ y_id ->
237 returnDs (mkValLam [y_id] (core_op `App` x_atom `App` VarArg y_id))
239 -- dsExpr (SectionR op expr) -- \ x -> op x expr
240 dsExpr (SectionR op expr)
241 = dsExpr op `thenDs` \ core_op ->
242 -- for the type of x, we need the type of op's 2nd argument
244 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
246 dsExpr expr `thenDs` \ y_expr ->
247 dsExprToAtomGivenTy y_expr y_ty $ \ y_atom ->
249 newSysLocalDs x_ty `thenDs` \ x_id ->
250 returnDs (mkValLam [x_id] (core_op `App` VarArg x_id `App` y_atom))
252 dsExpr (CCall label args may_gc is_asm result_ty)
253 = mapDs dsExpr args `thenDs` \ core_args ->
254 dsCCall label core_args may_gc is_asm result_ty
255 -- dsCCall does all the unboxification, etc.
257 dsExpr (HsSCC cc expr)
258 = dsExpr expr `thenDs` \ core_expr ->
259 getModuleAndGroupDs `thenDs` \ (mod_name, group_name) ->
260 returnDs ( SCC (mkUserCC cc mod_name group_name) core_expr)
262 dsExpr expr@(HsCase discrim matches src_loc)
263 = putSrcLocDs src_loc $
264 dsExpr discrim `thenDs` \ core_discrim ->
265 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
266 returnDs ( mkCoLetAny (NonRec discrim_var core_discrim) matching_code )
268 dsExpr (HsLet binds expr)
269 = dsBinds False binds `thenDs` \ core_binds ->
270 dsExpr expr `thenDs` \ core_expr ->
271 returnDs ( mkCoLetsAny core_binds core_expr )
273 dsExpr (HsDoOut do_or_lc stmts return_id then_id zero_id result_ty src_loc)
274 | maybeToBool maybe_list_comp
275 = -- Special case for list comprehensions
276 putSrcLocDs src_loc $
277 dsListComp stmts elt_ty
280 = putSrcLocDs src_loc $
281 dsDo do_or_lc stmts return_id then_id zero_id result_ty
284 = case (do_or_lc, splitTyConApp_maybe result_ty) of
285 (ListComp, Just (tycon, [elt_ty]))
289 -- We need the ListComp form to use deListComp (rather than the "do" form)
290 -- because the "return" in a do block is a call to "PrelBase.return", and
291 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
293 Just elt_ty = maybe_list_comp
295 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
296 = putSrcLocDs src_loc $
297 dsExpr guard_expr `thenDs` \ core_guard ->
298 dsExpr then_expr `thenDs` \ core_then ->
299 dsExpr else_expr `thenDs` \ core_else ->
300 returnDs (mkCoreIfThenElse core_guard core_then core_else)
304 Type lambda and application
305 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
307 dsExpr (TyLam tyvars expr)
308 = dsExpr expr `thenDs` \ core_expr ->
309 returnDs (mkTyLam tyvars core_expr)
311 dsExpr (TyApp expr tys)
312 = dsExpr expr `thenDs` \ core_expr ->
313 returnDs (mkTyApp core_expr tys)
317 Various data construction things
318 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
320 dsExpr (ExplicitListOut ty xs)
323 list_ty = mkListTy ty
325 -- xs can ocasaionlly be huge, so don't try to take
326 -- coreExprType of core_xs, as dsArgToAtom does
327 -- (that gives a quadratic algorithm)
328 go [] = returnDs (mk_nil_con ty)
329 go (x:xs) = dsExpr x `thenDs` \ core_x ->
330 dsExprToAtomGivenTy core_x ty $ \ arg_x ->
331 go xs `thenDs` \ core_xs ->
332 dsExprToAtomGivenTy core_xs list_ty $ \ arg_xs ->
333 returnDs (Con consDataCon [TyArg ty, arg_x, arg_xs])
335 dsExpr (ExplicitTuple expr_list)
336 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
337 mkConDs (tupleCon (length expr_list))
338 (map (TyArg . coreExprType) core_exprs ++ map VarArg core_exprs)
340 dsExpr (HsCon con_id [ty] [arg])
342 = dsExpr arg `thenDs` \ arg' ->
343 returnDs (Coerce (CoerceIn con_id) result_ty arg')
345 result_ty = mkTyConApp tycon [ty]
346 tycon = dataConTyCon con_id
348 dsExpr (HsCon con_id tys args)
349 = mapDs dsExpr args `thenDs` \ args2 ->
350 mkConDs con_id (map TyArg tys ++ map VarArg args2)
352 dsExpr (ArithSeqOut expr (From from))
353 = dsExpr expr `thenDs` \ expr2 ->
354 dsExpr from `thenDs` \ from2 ->
355 mkAppDs expr2 [VarArg from2]
357 dsExpr (ArithSeqOut expr (FromTo from two))
358 = dsExpr expr `thenDs` \ expr2 ->
359 dsExpr from `thenDs` \ from2 ->
360 dsExpr two `thenDs` \ two2 ->
361 mkAppDs expr2 [VarArg from2, VarArg two2]
363 dsExpr (ArithSeqOut expr (FromThen from thn))
364 = dsExpr expr `thenDs` \ expr2 ->
365 dsExpr from `thenDs` \ from2 ->
366 dsExpr thn `thenDs` \ thn2 ->
367 mkAppDs expr2 [VarArg from2, VarArg thn2]
369 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
370 = dsExpr expr `thenDs` \ expr2 ->
371 dsExpr from `thenDs` \ from2 ->
372 dsExpr thn `thenDs` \ thn2 ->
373 dsExpr two `thenDs` \ two2 ->
374 mkAppDs expr2 [VarArg from2, VarArg thn2, VarArg two2]
377 Record construction and update
378 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
379 For record construction we do this (assuming T has three arguments)
383 let err = /\a -> recConErr a
384 T (recConErr t1 "M.lhs/230/op1")
386 (recConErr t1 "M.lhs/230/op3")
388 recConErr then converts its arugment string into a proper message
389 before printing it as
391 M.lhs, line 230: missing field op1 was evaluated
395 dsExpr (RecordCon con_id con_expr rbinds)
396 = dsExpr con_expr `thenDs` \ con_expr' ->
398 (arg_tys, _) = splitFunTys (coreExprType con_expr')
401 = case [rhs | (sel_id,rhs,_) <- rbinds,
402 lbl == recordSelectorFieldLabel sel_id] of
403 (rhs:rhss) -> ASSERT( null rhss )
405 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showForErr lbl)
407 mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys (dataConFieldLabels con_id)) `thenDs` \ con_args ->
408 mkAppDs con_expr' (map VarArg con_args)
411 Record update is a little harder. Suppose we have the decl:
413 data T = T1 {op1, op2, op3 :: Int}
414 | T2 {op4, op2 :: Int}
417 Then we translate as follows:
423 T1 op1 _ op3 -> T1 op1 op2 op3
424 T2 op4 _ -> T2 op4 op2
425 other -> recUpdError "M.lhs/230"
427 It's important that we use the constructor Ids for T1, T2 etc on the
428 RHSs, and do not generate a Core Con directly, because the constructor
429 might do some argument-evaluation first; and may have to throw away some
433 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
434 = dsExpr record_expr `thenDs` \ record_expr' ->
436 -- Desugar the rbinds, and generate let-bindings if
437 -- necessary so that we don't lose sharing
438 dsRbinds rbinds $ \ rbinds' ->
440 record_in_ty = coreExprType record_expr'
441 (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
442 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
443 cons_to_upd = filter has_all_fields cons
445 -- initial_args are passed to every constructor
446 initial_args = map TyArg out_inst_tys ++ map VarArg dicts
448 mk_val_arg (field, arg_id)
449 = case [arg | (f, arg) <- rbinds',
450 field == recordSelectorFieldLabel f] of
451 (arg:args) -> ASSERT(null args)
456 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
458 val_args = map mk_val_arg (zipEqual "dsExpr:RecordUpd" (dataConFieldLabels con) arg_ids)
460 returnDs (con, arg_ids, mkGenApp (mkGenApp (Var con) initial_args) val_args)
463 | length cons_to_upd == length cons
466 = newSysLocalDs record_in_ty `thenDs` \ deflt_id ->
467 mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty "" `thenDs` \ err ->
468 returnDs (BindDefault deflt_id err)
470 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
471 mk_default `thenDs` \ deflt ->
473 returnDs (Case record_expr' (AlgAlts alts deflt))
476 has_all_fields :: Id -> Bool
477 has_all_fields con_id
480 con_fields = dataConFieldLabels con_id
481 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
484 Dictionary lambda and application
485 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
486 @DictLam@ and @DictApp@ turn into the regular old things.
487 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
488 complicated; reminiscent of fully-applied constructors.
490 dsExpr (DictLam dictvars expr)
491 = dsExpr expr `thenDs` \ core_expr ->
492 returnDs (mkValLam dictvars core_expr)
496 dsExpr (DictApp expr dicts) -- becomes a curried application
497 = mapDs lookupEnvDs dicts `thenDs` \ core_dicts ->
498 dsExpr expr `thenDs` \ core_expr ->
499 returnDs (foldl (\f d -> f `App` (VarArg d)) core_expr core_dicts)
506 -- HsSyn constructs that just shouldn't be here:
507 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
508 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
509 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
510 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
513 out_of_range_msg -- ditto
514 = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
518 %--------------------------------------------------------------------
522 = lookupEnvDs v `thenDs` \ v' ->
527 dsRbinds :: TypecheckedRecordBinds -- The field bindings supplied
528 -> ([(Id, CoreArg)] -> DsM CoreExpr) -- A continuation taking the field
529 -- bindings with atomic rhss
530 -> DsM CoreExpr -- The result of the continuation,
531 -- wrapped in suitable Lets
533 dsRbinds [] continue_with
536 dsRbinds ((sel_id, rhs, pun_flag) : rbinds) continue_with
537 = dsExpr rhs `thenDs` \ rhs' ->
538 dsExprToAtomGivenTy rhs' (coreExprType rhs') $ \ rhs_atom ->
539 dsRbinds rbinds $ \ rbinds' ->
540 continue_with ((sel_id, rhs_atom) : rbinds')
544 -- do_unfold ty_env val_env (Lam (TyBinder tyvar) body) (TyArg ty : args)
545 -- = do_unfold (addToTyVarEnv ty_env tyvar ty) val_env body args
547 -- do_unfold ty_env val_env (Lam (ValBinder binder) body) (arg@(VarArg expr) : args)
548 -- = dsExprToAtom arg $ \ arg_atom ->
550 -- (addOneToIdEnv val_env binder (argToExpr arg_atom))
553 -- do_unfold ty_env val_env body args
554 -- = -- Clone the remaining part of the template
555 -- uniqSMtoDsM (substCoreExpr val_env ty_env body) `thenDs` \ body' ->
557 -- -- Apply result to remaining arguments
558 -- mkAppDs body' args
561 Basically does the translation given in the Haskell~1.3 report:
565 -> Id -- id for: return m
566 -> Id -- id for: (>>=) m
567 -> Id -- id for: zero m
568 -> Type -- Element type; the whole expression has type (m t)
571 dsDo do_or_lc stmts return_id then_id zero_id result_ty
572 = dsId return_id `thenDs` \ return_ds ->
573 dsId then_id `thenDs` \ then_ds ->
574 dsId zero_id `thenDs` \ zero_ds ->
576 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
579 = dsExpr expr `thenDs` \ expr2 ->
580 mkAppDs return_ds [TyArg b_ty, VarArg expr2]
582 go (GuardStmt expr locn : stmts)
583 = do_expr expr locn `thenDs` \ expr2 ->
584 go stmts `thenDs` \ rest ->
585 mkAppDs zero_ds [TyArg b_ty] `thenDs` \ zero_expr ->
586 returnDs (mkCoreIfThenElse expr2 rest zero_expr)
588 go (ExprStmt expr locn : stmts)
589 = do_expr expr locn `thenDs` \ expr2 ->
591 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
596 go stmts `thenDs` \ rest ->
597 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
598 mkAppDs then_ds [TyArg a_ty, TyArg b_ty, VarArg expr2,
599 VarArg (mkValLam [ignored_result_id] rest)]
601 go (LetStmt binds : stmts )
602 = dsBinds False binds `thenDs` \ binds2 ->
603 go stmts `thenDs` \ rest ->
604 returnDs (mkCoLetsAny binds2 rest)
606 go (BindStmt pat expr locn : stmts)
608 dsExpr expr `thenDs` \ expr2 ->
610 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
611 zero_expr = TyApp (HsVar zero_id) [b_ty]
612 main_match = PatMatch pat (SimpleMatch (
613 HsDoOut do_or_lc stmts return_id then_id zero_id result_ty locn))
615 = if failureFreePat pat
617 else [main_match, PatMatch (WildPat a_ty) (SimpleMatch zero_expr)]
619 matchWrapper DoBindMatch the_matches match_msg
620 `thenDs` \ (binders, matching_code) ->
621 mkAppDs then_ds [TyArg a_ty, TyArg b_ty,
622 VarArg expr2, VarArg (mkValLam binders matching_code)]
627 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
629 match_msg = case do_or_lc of
630 DoStmt -> "`do' statement"
631 ListComp -> "comprehension"