2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[DsExpr]{Matching expressions (Exprs)}
7 #include "HsVersions.h"
9 module DsExpr ( dsExpr ) where
12 import DsLoop -- partly to get dsBinds, partly to chk dsExpr
14 import HsSyn ( HsExpr(..), HsLit(..), ArithSeqInfo(..),
15 Match, Qual, HsBinds, Stmt, PolyType )
16 import TcHsSyn ( TypecheckedHsExpr(..), TypecheckedHsBinds(..),
17 TypecheckedRecordBinds(..)
22 import DsCCall ( dsCCall )
23 import DsListComp ( dsListComp )
24 import DsUtils ( mkAppDs, mkConDs, mkPrimDs, dsExprToAtom,
25 mkErrorAppDs, showForErr
27 import Match ( matchWrapper )
29 import CoreUnfold ( UnfoldingDetails(..), UnfoldingGuidance(..),
31 import CoreUtils ( coreExprType, substCoreExpr, argToExpr,
32 mkCoreIfThenElse, unTagBinders )
33 import CostCentre ( mkUserCC )
34 import FieldLabel ( fieldLabelType, FieldLabel )
35 import Id ( mkTupleCon, idType, nullIdEnv, addOneToIdEnv,
36 getIdUnfolding, dataConArgTys, dataConFieldLabels,
37 recordSelectorFieldLabel
39 import Literal ( mkMachInt, Literal(..) )
40 import MagicUFs ( MagicUnfoldingFun )
41 import PprStyle ( PprStyle(..) )
42 import PprType ( GenType )
43 import PrelInfo ( mkTupleTy, unitTy, nilDataCon, consDataCon,
44 charDataCon, charTy, rEC_CON_ERROR_ID,
47 import Pretty ( ppShow, ppBesides, ppPStr, ppStr )
48 import TyCon ( isDataTyCon, isNewTyCon )
49 import Type ( splitSigmaTy, splitFunTy, typePrimRep,
50 getAppDataTyCon, getAppTyCon, applyTy
52 import TyVar ( nullTyVarEnv, addOneToTyVarEnv, GenTyVar{-instance Eq-} )
53 import Usage ( UVar(..) )
54 import Util ( zipEqual, pprError, panic, assertPanic )
56 maybeBoxedPrimType = panic "DsExpr.maybeBoxedPrimType"
57 splitTyArgs = panic "DsExpr.splitTyArgs"
59 mk_nil_con ty = mkCon nilDataCon [] [ty] [] -- micro utility...
62 The funny business to do with variables is that we look them up in the
63 Id-to-Id and Id-to-Id maps that the monadery is carrying
64 around; if we get hits, we use the value accordingly.
66 %************************************************************************
68 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
70 %************************************************************************
73 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
75 dsExpr (HsVar var) = dsApp (HsVar var) []
78 %************************************************************************
80 \subsection[DsExpr-literals]{Literals}
82 %************************************************************************
84 We give int/float literals type Integer and Rational, respectively.
85 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
88 ToDo: put in range checks for when converting "i"
89 (or should that be in the typechecker?)
91 For numeric literals, we try to detect there use at a standard type
92 (Int, Float, etc.) are directly put in the right constructor.
93 [NB: down with the @App@ conversion.]
94 Otherwise, we punt, putting in a "NoRep" Core literal (where the
95 representation decisions are delayed)...
97 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
100 dsExpr (HsLitOut (HsString s) _)
102 = returnDs (mk_nil_con charTy)
106 the_char = mkCon charDataCon [] [] [LitArg (MachChar (_HEAD_ s))]
107 the_nil = mk_nil_con charTy
109 mkConDs consDataCon [charTy] [the_char, the_nil]
111 -- "_" => build (\ c n -> c 'c' n) -- LATER
113 -- "str" ==> build (\ c n -> foldr charTy T c n "str")
116 dsExpr (HsLitOut (HsString str) _)
117 = newTyVarsDs [alphaTyVar] `thenDs` \ [new_tyvar] ->
119 new_ty = mkTyVarTy new_tyvar
122 charTy `mkFunTy` (new_ty `mkFunTy` new_ty),
124 mkForallTy [alphaTyVar]
125 ((charTy `mkFunTy` (alphaTy `mkFunTy` alphaTy))
126 `mkFunTy` (alphaTy `mkFunTy` alphaTy))
127 ] `thenDs` \ [c,n,g] ->
128 returnDs (mkBuild charTy new_tyvar c n g (
130 (CoTyApp (CoTyApp (Var foldrId) charTy) new_ty) *** ensure non-prim type ***
131 [VarArg c,VarArg n,LitArg (NoRepStr str)]))
134 -- otherwise, leave it as a NoRepStr;
135 -- the Core-to-STG pass will wrap it in an application of "unpackCStringId".
137 dsExpr (HsLitOut (HsString str) _)
138 = returnDs (Lit (NoRepStr str))
140 dsExpr (HsLitOut (HsLitLit s) ty)
141 = returnDs ( mkCon data_con [] [] [LitArg (MachLitLit s kind)] )
144 = case (maybeBoxedPrimType ty) of
145 Just (boxing_data_con, prim_ty)
146 -> (boxing_data_con, typePrimRep prim_ty)
148 -> pprError "ERROR: ``literal-literal'' not a single-constructor type: "
149 (ppBesides [ppPStr s, ppStr "; type: ", ppr PprDebug ty])
151 dsExpr (HsLitOut (HsInt i) _)
152 = returnDs (Lit (NoRepInteger i))
154 dsExpr (HsLitOut (HsFrac r) _)
155 = returnDs (Lit (NoRepRational r))
157 -- others where we know what to do:
159 dsExpr (HsLitOut (HsIntPrim i) _)
160 = if (i >= toInteger minInt && i <= toInteger maxInt) then
161 returnDs (Lit (mkMachInt i))
163 error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
165 dsExpr (HsLitOut (HsFloatPrim f) _)
166 = returnDs (Lit (MachFloat f))
167 -- ToDo: range checking needed!
169 dsExpr (HsLitOut (HsDoublePrim d) _)
170 = returnDs (Lit (MachDouble d))
171 -- ToDo: range checking needed!
173 dsExpr (HsLitOut (HsChar c) _)
174 = returnDs ( mkCon charDataCon [] [] [LitArg (MachChar c)] )
176 dsExpr (HsLitOut (HsCharPrim c) _)
177 = returnDs (Lit (MachChar c))
179 dsExpr (HsLitOut (HsStringPrim s) _)
180 = returnDs (Lit (MachStr s))
182 -- end of literals magic. --
184 dsExpr expr@(HsLam a_Match)
185 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
186 returnDs ( mkValLam binders matching_code )
188 dsExpr expr@(HsApp e1 e2) = dsApp expr []
189 dsExpr expr@(OpApp e1 op e2) = dsApp expr []
192 Operator sections. At first it looks as if we can convert
201 But no! expr might be a redex, and we can lose laziness badly this
206 for example. So we convert instead to
208 let y = expr in \x -> op y x
210 If \tr{expr} is actually just a variable, say, then the simplifier
214 dsExpr (SectionL expr op)
215 = dsExpr op `thenDs` \ core_op ->
216 dsExpr expr `thenDs` \ core_expr ->
217 dsExprToAtom core_expr $ \ y_atom ->
219 -- for the type of x, we need the type of op's 2nd argument
221 x_ty = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
222 case (splitTyArgs tau_ty) of {
223 ((_:arg2_ty:_), _) -> arg2_ty;
224 _ -> panic "dsExpr:SectionL:arg 2 ty"
227 newSysLocalDs x_ty `thenDs` \ x_id ->
228 returnDs (mkValLam [x_id] (core_op `App` y_atom `App` VarArg x_id))
230 -- dsExpr (SectionR op expr) -- \ x -> op x expr
231 dsExpr (SectionR op expr)
232 = dsExpr op `thenDs` \ core_op ->
233 dsExpr expr `thenDs` \ core_expr ->
234 dsExprToAtom core_expr $ \ y_atom ->
236 -- for the type of x, we need the type of op's 1st argument
238 x_ty = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
239 case (splitTyArgs tau_ty) of {
240 ((arg1_ty:_), _) -> arg1_ty;
241 _ -> panic "dsExpr:SectionR:arg 1 ty"
244 newSysLocalDs x_ty `thenDs` \ x_id ->
245 returnDs (mkValLam [x_id] (core_op `App` VarArg x_id `App` y_atom))
247 dsExpr (CCall label args may_gc is_asm result_ty)
248 = mapDs dsExpr args `thenDs` \ core_args ->
249 dsCCall label core_args may_gc is_asm result_ty
250 -- dsCCall does all the unboxification, etc.
252 dsExpr (HsSCC cc expr)
253 = dsExpr expr `thenDs` \ core_expr ->
254 getModuleAndGroupDs `thenDs` \ (mod_name, group_name) ->
255 returnDs ( SCC (mkUserCC cc mod_name group_name) core_expr)
257 dsExpr expr@(HsCase discrim matches src_loc)
258 = putSrcLocDs src_loc $
259 dsExpr discrim `thenDs` \ core_discrim ->
260 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
261 returnDs ( mkCoLetAny (NonRec discrim_var core_discrim) matching_code )
263 dsExpr (ListComp expr quals)
264 = dsExpr expr `thenDs` \ core_expr ->
265 dsListComp core_expr quals
267 dsExpr (HsLet binds expr)
268 = dsBinds binds `thenDs` \ core_binds ->
269 dsExpr expr `thenDs` \ core_expr ->
270 returnDs ( mkCoLetsAny core_binds core_expr )
272 dsExpr (HsDoOut stmts m_id mz_id src_loc)
273 = putSrcLocDs src_loc $
274 panic "dsExpr:HsDoOut"
276 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
277 = putSrcLocDs src_loc $
278 dsExpr guard_expr `thenDs` \ core_guard ->
279 dsExpr then_expr `thenDs` \ core_then ->
280 dsExpr else_expr `thenDs` \ core_else ->
281 returnDs (mkCoreIfThenElse core_guard core_then core_else)
286 Type lambda and application
287 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
289 dsExpr (TyLam tyvars expr)
290 = dsExpr expr `thenDs` \ core_expr ->
291 returnDs (mkTyLam tyvars core_expr)
293 dsExpr expr@(TyApp e tys) = dsApp expr []
297 Various data construction things
298 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
300 dsExpr (ExplicitListOut ty xs)
302 [] -> returnDs (mk_nil_con ty)
304 dsExpr y `thenDs` \ core_hd ->
305 dsExpr (ExplicitListOut ty ys) `thenDs` \ core_tl ->
306 mkConDs consDataCon [ty] [core_hd, core_tl]
308 dsExpr (ExplicitTuple expr_list)
309 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
310 mkConDs (mkTupleCon (length expr_list))
311 (map coreExprType core_exprs)
314 -- Two cases, one for ordinary constructors and one for newtype constructors
315 dsExpr (HsCon con tys args)
316 | isDataTyCon tycon -- The usual datatype case
317 = mapDs dsExpr args `thenDs` \ args_exprs ->
318 mkConDs con tys args_exprs
320 | otherwise -- The newtype case
321 = ASSERT( isNewTyCon tycon )
322 ASSERT( null rest_args )
323 dsExpr first_arg `thenDs` \ arg_expr ->
324 returnDs (Coerce (CoerceIn con) result_ty arg_expr)
327 (first_arg:rest_args) = args
328 (args_tys, result_ty) = splitFunTy (foldl applyTy (idType con) tys)
329 (tycon,_) = getAppTyCon result_ty
331 dsExpr (ArithSeqOut expr (From from))
332 = dsExpr expr `thenDs` \ expr2 ->
333 dsExpr from `thenDs` \ from2 ->
334 mkAppDs expr2 [] [from2]
336 dsExpr (ArithSeqOut expr (FromTo from two))
337 = dsExpr expr `thenDs` \ expr2 ->
338 dsExpr from `thenDs` \ from2 ->
339 dsExpr two `thenDs` \ two2 ->
340 mkAppDs expr2 [] [from2, two2]
342 dsExpr (ArithSeqOut expr (FromThen from thn))
343 = dsExpr expr `thenDs` \ expr2 ->
344 dsExpr from `thenDs` \ from2 ->
345 dsExpr thn `thenDs` \ thn2 ->
346 mkAppDs expr2 [] [from2, thn2]
348 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
349 = dsExpr expr `thenDs` \ expr2 ->
350 dsExpr from `thenDs` \ from2 ->
351 dsExpr thn `thenDs` \ thn2 ->
352 dsExpr two `thenDs` \ two2 ->
353 mkAppDs expr2 [] [from2, thn2, two2]
356 Record construction and update
357 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
358 For record construction we do this (assuming T has three arguments)
362 let err = /\a -> recConErr a
363 T (recConErr t1 "M.lhs/230/op1")
365 (recConErr t1 "M.lhs/230/op3")
367 recConErr then converts its arugment string into a proper message
368 before printing it as
370 M.lhs, line 230: missing field op1 was evaluated
374 dsExpr (RecordCon con_expr rbinds)
375 = dsExpr con_expr `thenDs` \ con_expr' ->
377 con_id = get_con con_expr'
378 (arg_tys, _) = splitFunTy (coreExprType con_expr')
381 = case [rhs | (sel_id,rhs,_) <- rbinds,
382 lbl == recordSelectorFieldLabel sel_id] of
383 (rhs:rhss) -> ASSERT( null rhss )
385 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showForErr lbl)
387 mapDs mk_arg (arg_tys `zipEqual` dataConFieldLabels con_id) `thenDs` \ con_args ->
388 mkAppDs con_expr' [] con_args
390 -- "con_expr'" is simply an application of the constructor Id
391 -- to types and (perhaps) dictionaries. This gets the constructor...
392 get_con (Var con) = con
393 get_con (App fun _) = get_con fun
396 Record update is a little harder. Suppose we have the decl:
398 data T = T1 {op1, op2, op3 :: Int}
399 | T2 {op4, op2 :: Int}
402 Then we translate as follows:
408 T1 op1 _ op3 -> T1 op1 op2 op3
409 T2 op4 _ -> T2 op4 op2
410 other -> recUpdError "M.lhs/230"
412 It's important that we use the constructor Ids for T1, T2 etc on the
413 RHSs, and do not generate a Core Con directly, because the constructor
414 might do some argument-evaluation first; and may have to throw away some
418 dsExpr (RecordUpdOut record_expr dicts rbinds)
419 = dsExpr record_expr `thenDs` \ record_expr' ->
421 -- Desugar the rbinds, and generate let-bindings if
422 -- necessary so that we don't lose sharing
423 dsRbinds rbinds $ \ rbinds' ->
425 record_ty = coreExprType record_expr'
426 (tycon, inst_tys, cons) = _trace "getAppDataTyCon.DsExpr" $ getAppDataTyCon record_ty
427 cons_to_upd = filter has_all_fields cons
429 -- initial_args are passed to every constructor
430 initial_args = map TyArg inst_tys ++ map VarArg dicts
432 mk_val_arg (field, arg_id)
433 = case [arg | (f, arg) <- rbinds',
434 field == recordSelectorFieldLabel f] of
435 (arg:args) -> ASSERT(null args)
440 = newSysLocalsDs (dataConArgTys con inst_tys) `thenDs` \ arg_ids ->
442 val_args = map mk_val_arg (dataConFieldLabels con `zipEqual` arg_ids)
444 returnDs (con, arg_ids, mkGenApp (mkGenApp (Var con) initial_args) val_args)
447 | length cons_to_upd == length cons
450 = newSysLocalDs record_ty `thenDs` \ deflt_id ->
451 mkErrorAppDs rEC_UPD_ERROR_ID record_ty "" `thenDs` \ err ->
452 returnDs (BindDefault deflt_id err)
454 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
455 mk_default `thenDs` \ deflt ->
457 returnDs (Case record_expr' (AlgAlts alts deflt))
460 has_all_fields :: Id -> Bool
461 has_all_fields con_id
464 con_fields = dataConFieldLabels con_id
465 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
468 Dictionary lambda and application
469 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
470 @DictLam@ and @DictApp@ turn into the regular old things.
471 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
472 complicated; reminiscent of fully-applied constructors.
474 dsExpr (DictLam dictvars expr)
475 = dsExpr expr `thenDs` \ core_expr ->
476 returnDs( mkValLam dictvars core_expr )
480 dsExpr expr@(DictApp e dicts) -- becomes a curried application
484 @SingleDicts@ become @Locals@; @Dicts@ turn into tuples, unless
486 @ClassDictLam dictvars methods expr@ is ``the opposite'':
488 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
491 dsExpr (SingleDict dict) -- just a local
492 = lookupEnvWithDefaultDs dict (Var dict)
494 dsExpr (Dictionary dicts methods)
495 = -- hey, these things may have been substituted away...
496 zipWithDs lookupEnvWithDefaultDs
497 dicts_and_methods dicts_and_methods_exprs
498 `thenDs` \ core_d_and_ms ->
500 (case num_of_d_and_ms of
501 0 -> returnDs cocon_unit -- unit
503 1 -> returnDs (head core_d_and_ms) -- just a single Id
506 mkConDs (mkTupleCon num_of_d_and_ms)
507 (map coreExprType core_d_and_ms)
511 dicts_and_methods = dicts ++ methods
512 dicts_and_methods_exprs = map Var dicts_and_methods
513 num_of_d_and_ms = length dicts_and_methods
515 dsExpr (ClassDictLam dicts methods expr)
516 = dsExpr expr `thenDs` \ core_expr ->
517 case num_of_d_and_ms of
518 0 -> newSysLocalDs unitTy `thenDs` \ new_x ->
519 returnDs (mkValLam [new_x] core_expr)
522 returnDs (mkValLam dicts_and_methods core_expr)
525 newSysLocalDs tuple_ty `thenDs` \ new_x ->
527 Lam (ValBinder new_x)
530 [(tuple_con, dicts_and_methods, core_expr)]
533 num_of_d_and_ms = length dicts + length methods
534 dicts_and_methods = dicts ++ methods
535 tuple_ty = mkTupleTy num_of_d_and_ms (map idType dicts_and_methods)
536 tuple_con = mkTupleCon num_of_d_and_ms
539 -- HsSyn constructs that just shouldn't be here:
540 dsExpr (HsDo _ _) = panic "dsExpr:HsDo"
541 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
542 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
543 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
546 cocon_unit = mkCon (mkTupleCon 0) [] [] [] -- out here to avoid CAF (sigh)
547 out_of_range_msg -- ditto
548 = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
551 %--------------------------------------------------------------------
553 @(dsApp e [t_1,..,t_n, e_1,..,e_n])@ returns something with the same
556 e t_1 ... t_n e_1 .. e_n
559 We're doing all this so we can saturate constructors (as painlessly as
563 type DsCoreArg = GenCoreArg CoreExpr{-NB!-} TyVar UVar
565 dsApp :: TypecheckedHsExpr -- expr to desugar
566 -> [DsCoreArg] -- accumulated ty/val args: NB:
567 -> DsM CoreExpr -- final result
569 dsApp (HsApp e1 e2) args
570 = dsExpr e2 `thenDs` \ core_e2 ->
571 dsApp e1 (VarArg core_e2 : args)
573 dsApp (OpApp e1 op e2) args
574 = dsExpr e1 `thenDs` \ core_e1 ->
575 dsExpr e2 `thenDs` \ core_e2 ->
576 dsApp op (VarArg core_e1 : VarArg core_e2 : args)
578 dsApp (DictApp expr dicts) args
579 = -- now, those dicts may have been substituted away...
580 zipWithDs lookupEnvWithDefaultDs dicts (map Var dicts)
581 `thenDs` \ core_dicts ->
582 dsApp expr (map VarArg core_dicts ++ args)
584 dsApp (TyApp expr tys) args
585 = dsApp expr (map TyArg tys ++ args)
587 -- we might should look out for SectionLs, etc., here, but we don't
590 = lookupEnvDs v `thenDs` \ maybe_expr ->
592 Just expr -> apply_to_args expr args
594 Nothing -> -- we're only saturating constructors and PrimOps
595 case getIdUnfolding v of
596 GenForm _ _ the_unfolding EssentialUnfolding
597 -> do_unfold nullTyVarEnv nullIdEnv (unTagBinders the_unfolding) args
599 _ -> apply_to_args (Var v) args
602 dsApp anything_else args
603 = dsExpr anything_else `thenDs` \ core_expr ->
604 apply_to_args core_expr args
606 -- a DsM version of mkGenApp:
607 apply_to_args :: CoreExpr -> [DsCoreArg] -> DsM CoreExpr
609 apply_to_args fun args
611 (ty_args, val_args) = foldr sep ([],[]) args
613 mkAppDs fun ty_args val_args
615 sep a@(LitArg l) (tys,vals) = (tys, (Lit l):vals)
616 sep a@(VarArg e) (tys,vals) = (tys, e:vals)
617 sep a@(TyArg ty) (tys,vals) = (ty:tys, vals)
618 sep a@(UsageArg _) _ = panic "DsExpr:apply_to_args:UsageArg"
623 dsRbinds :: TypecheckedRecordBinds -- The field bindings supplied
624 -> ([(Id, CoreArg)] -> DsM CoreExpr) -- A continuation taking the field
625 -- bindings with atomic rhss
626 -> DsM CoreExpr -- The result of the continuation,
627 -- wrapped in suitable Lets
629 dsRbinds [] continue_with
632 dsRbinds ((sel_id, rhs, pun_flag) : rbinds) continue_with
633 = dsExpr rhs `thenDs` \ rhs' ->
634 dsExprToAtom rhs' $ \ rhs_atom ->
635 dsRbinds rbinds $ \ rbinds' ->
636 continue_with ((sel_id, rhs_atom) : rbinds')
640 do_unfold ty_env val_env (Lam (TyBinder tyvar) body) (TyArg ty : args)
641 = do_unfold (addOneToTyVarEnv ty_env tyvar ty) val_env body args
643 do_unfold ty_env val_env (Lam (ValBinder binder) body) (VarArg expr : args)
644 = dsExprToAtom expr $ \ arg_atom ->
646 (addOneToIdEnv val_env binder (argToExpr arg_atom))
649 do_unfold ty_env val_env body args
650 = -- Clone the remaining part of the template
651 uniqSMtoDsM (substCoreExpr val_env ty_env body) `thenDs` \ body' ->
653 -- Apply result to remaining arguments
654 apply_to_args body' args