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 ( FieldLabel{-instance Eq/Outputable-} )
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 Type ( splitSigmaTy, splitFunTy, typePrimRep,
51 import TyVar ( nullTyVarEnv, addOneToTyVarEnv )
52 import Usage ( UVar(..) )
53 import Util ( zipEqual, pprError, panic, assertPanic )
55 maybeBoxedPrimType = panic "DsExpr.maybeBoxedPrimType"
56 splitTyArgs = panic "DsExpr.splitTyArgs"
58 mk_nil_con ty = mkCon nilDataCon [] [ty] [] -- micro utility...
61 The funny business to do with variables is that we look them up in the
62 Id-to-Id and Id-to-Id maps that the monadery is carrying
63 around; if we get hits, we use the value accordingly.
65 %************************************************************************
67 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
69 %************************************************************************
72 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
74 dsExpr (HsVar var) = dsApp (HsVar var) []
77 %************************************************************************
79 \subsection[DsExpr-literals]{Literals}
81 %************************************************************************
83 We give int/float literals type Integer and Rational, respectively.
84 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
87 ToDo: put in range checks for when converting "i"
88 (or should that be in the typechecker?)
90 For numeric literals, we try to detect there use at a standard type
91 (Int, Float, etc.) are directly put in the right constructor.
92 [NB: down with the @App@ conversion.]
93 Otherwise, we punt, putting in a "NoRep" Core literal (where the
94 representation decisions are delayed)...
96 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
99 dsExpr (HsLitOut (HsString s) _)
101 = returnDs (mk_nil_con charTy)
105 the_char = mkCon charDataCon [] [] [LitArg (MachChar (_HEAD_ s))]
106 the_nil = mk_nil_con charTy
108 mkConDs consDataCon [charTy] [the_char, the_nil]
110 -- "_" => build (\ c n -> c 'c' n) -- LATER
112 -- "str" ==> build (\ c n -> foldr charTy T c n "str")
115 dsExpr (HsLitOut (HsString str) _)
116 = newTyVarsDs [alphaTyVar] `thenDs` \ [new_tyvar] ->
118 new_ty = mkTyVarTy new_tyvar
121 charTy `mkFunTy` (new_ty `mkFunTy` new_ty),
123 mkForallTy [alphaTyVar]
124 ((charTy `mkFunTy` (alphaTy `mkFunTy` alphaTy))
125 `mkFunTy` (alphaTy `mkFunTy` alphaTy))
126 ] `thenDs` \ [c,n,g] ->
127 returnDs (mkBuild charTy new_tyvar c n g (
129 (CoTyApp (CoTyApp (Var foldrId) charTy) new_ty) *** ensure non-prim type ***
130 [VarArg c,VarArg n,LitArg (NoRepStr str)]))
133 -- otherwise, leave it as a NoRepStr;
134 -- the Core-to-STG pass will wrap it in an application of "unpackCStringId".
136 dsExpr (HsLitOut (HsString str) _)
137 = returnDs (Lit (NoRepStr str))
139 dsExpr (HsLitOut (HsLitLit s) ty)
140 = returnDs ( mkCon data_con [] [] [LitArg (MachLitLit s kind)] )
143 = case (maybeBoxedPrimType ty) of
144 Just (boxing_data_con, prim_ty)
145 -> (boxing_data_con, typePrimRep prim_ty)
147 -> pprError "ERROR: ``literal-literal'' not a single-constructor type: "
148 (ppBesides [ppPStr s, ppStr "; type: ", ppr PprDebug ty])
150 dsExpr (HsLitOut (HsInt i) _)
151 = returnDs (Lit (NoRepInteger i))
153 dsExpr (HsLitOut (HsFrac r) _)
154 = returnDs (Lit (NoRepRational r))
156 -- others where we know what to do:
158 dsExpr (HsLitOut (HsIntPrim i) _)
159 = if (i >= toInteger minInt && i <= toInteger maxInt) then
160 returnDs (Lit (mkMachInt i))
162 error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
164 dsExpr (HsLitOut (HsFloatPrim f) _)
165 = returnDs (Lit (MachFloat f))
166 -- ToDo: range checking needed!
168 dsExpr (HsLitOut (HsDoublePrim d) _)
169 = returnDs (Lit (MachDouble d))
170 -- ToDo: range checking needed!
172 dsExpr (HsLitOut (HsChar c) _)
173 = returnDs ( mkCon charDataCon [] [] [LitArg (MachChar c)] )
175 dsExpr (HsLitOut (HsCharPrim c) _)
176 = returnDs (Lit (MachChar c))
178 dsExpr (HsLitOut (HsStringPrim s) _)
179 = returnDs (Lit (MachStr s))
181 -- end of literals magic. --
183 dsExpr expr@(HsLam a_Match)
184 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
185 returnDs ( mkValLam binders matching_code )
187 dsExpr expr@(HsApp e1 e2) = dsApp expr []
188 dsExpr expr@(OpApp e1 op e2) = dsApp expr []
191 Operator sections. At first it looks as if we can convert
200 But no! expr might be a redex, and we can lose laziness badly this
205 for example. So we convert instead to
207 let y = expr in \x -> op y x
209 If \tr{expr} is actually just a variable, say, then the simplifier
213 dsExpr (SectionL expr op)
214 = dsExpr op `thenDs` \ core_op ->
215 dsExpr expr `thenDs` \ core_expr ->
216 dsExprToAtom core_expr $ \ y_atom ->
218 -- for the type of x, we need the type of op's 2nd argument
220 x_ty = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
221 case (splitTyArgs tau_ty) of {
222 ((_:arg2_ty:_), _) -> arg2_ty;
223 _ -> panic "dsExpr:SectionL:arg 2 ty"
226 newSysLocalDs x_ty `thenDs` \ x_id ->
227 returnDs (mkValLam [x_id] (core_op `App` y_atom `App` VarArg x_id))
229 -- dsExpr (SectionR op expr) -- \ x -> op x expr
230 dsExpr (SectionR op expr)
231 = dsExpr op `thenDs` \ core_op ->
232 dsExpr expr `thenDs` \ core_expr ->
233 dsExprToAtom core_expr $ \ y_atom ->
235 -- for the type of x, we need the type of op's 1st argument
237 x_ty = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
238 case (splitTyArgs tau_ty) of {
239 ((arg1_ty:_), _) -> arg1_ty;
240 _ -> panic "dsExpr:SectionR:arg 1 ty"
243 newSysLocalDs x_ty `thenDs` \ x_id ->
244 returnDs (mkValLam [x_id] (core_op `App` VarArg x_id `App` y_atom))
246 dsExpr (CCall label args may_gc is_asm result_ty)
247 = mapDs dsExpr args `thenDs` \ core_args ->
248 dsCCall label core_args may_gc is_asm result_ty
249 -- dsCCall does all the unboxification, etc.
251 dsExpr (HsSCC cc expr)
252 = dsExpr expr `thenDs` \ core_expr ->
253 getModuleAndGroupDs `thenDs` \ (mod_name, group_name) ->
254 returnDs ( SCC (mkUserCC cc mod_name group_name) core_expr)
256 dsExpr expr@(HsCase discrim matches src_loc)
257 = putSrcLocDs src_loc $
258 dsExpr discrim `thenDs` \ core_discrim ->
259 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
260 returnDs ( mkCoLetAny (NonRec discrim_var core_discrim) matching_code )
262 dsExpr (ListComp expr quals)
263 = dsExpr expr `thenDs` \ core_expr ->
264 dsListComp core_expr quals
266 dsExpr (HsLet binds expr)
267 = dsBinds binds `thenDs` \ core_binds ->
268 dsExpr expr `thenDs` \ core_expr ->
269 returnDs ( mkCoLetsAny core_binds core_expr )
271 dsExpr (HsDoOut stmts m_id mz_id src_loc)
272 = putSrcLocDs src_loc $
273 panic "dsExpr:HsDoOut"
275 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
276 = putSrcLocDs src_loc $
277 dsExpr guard_expr `thenDs` \ core_guard ->
278 dsExpr then_expr `thenDs` \ core_then ->
279 dsExpr else_expr `thenDs` \ core_else ->
280 returnDs (mkCoreIfThenElse core_guard core_then core_else)
285 Type lambda and application
286 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
288 dsExpr (TyLam tyvars expr)
289 = dsExpr expr `thenDs` \ core_expr ->
290 returnDs (mkTyLam tyvars core_expr)
292 dsExpr expr@(TyApp e tys) = dsApp expr []
296 Various data construction things
297 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
299 dsExpr (ExplicitListOut ty xs)
301 [] -> returnDs (mk_nil_con ty)
303 dsExpr y `thenDs` \ core_hd ->
304 dsExpr (ExplicitListOut ty ys) `thenDs` \ core_tl ->
305 mkConDs consDataCon [ty] [core_hd, core_tl]
307 dsExpr (ExplicitTuple expr_list)
308 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
309 mkConDs (mkTupleCon (length expr_list))
310 (map coreExprType core_exprs)
313 dsExpr (HsCon con tys args)
314 = mapDs dsExpr args `thenDs` \ args_exprs ->
315 mkConDs con tys args_exprs
317 dsExpr (ArithSeqOut expr (From from))
318 = dsExpr expr `thenDs` \ expr2 ->
319 dsExpr from `thenDs` \ from2 ->
320 mkAppDs expr2 [] [from2]
322 dsExpr (ArithSeqOut expr (FromTo from two))
323 = dsExpr expr `thenDs` \ expr2 ->
324 dsExpr from `thenDs` \ from2 ->
325 dsExpr two `thenDs` \ two2 ->
326 mkAppDs expr2 [] [from2, two2]
328 dsExpr (ArithSeqOut expr (FromThen from thn))
329 = dsExpr expr `thenDs` \ expr2 ->
330 dsExpr from `thenDs` \ from2 ->
331 dsExpr thn `thenDs` \ thn2 ->
332 mkAppDs expr2 [] [from2, thn2]
334 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
335 = dsExpr expr `thenDs` \ expr2 ->
336 dsExpr from `thenDs` \ from2 ->
337 dsExpr thn `thenDs` \ thn2 ->
338 dsExpr two `thenDs` \ two2 ->
339 mkAppDs expr2 [] [from2, thn2, two2]
342 Record construction and update
343 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
344 For record construction we do this (assuming T has three arguments)
348 let err = /\a -> recConErr a
349 T (recConErr t1 "M.lhs/230/op1")
351 (recConErr t1 "M.lhs/230/op3")
353 recConErr then converts its arugment string into a proper message
354 before printing it as
356 M.lhs, line 230: missing field op1 was evaluated
360 dsExpr (RecordCon con_expr rbinds)
361 = dsExpr con_expr `thenDs` \ con_expr' ->
363 con_id = get_con_id con_expr'
364 (arg_tys, data_ty) = splitFunTy (idType con_id)
366 mk_arg (arg_ty, lbl) = case [rhs | (sel_id,rhs,_) <- rbinds,
367 lbl == recordSelectorFieldLabel sel_id
369 (rhs:rhss) -> ASSERT( null rhss )
372 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showForErr lbl)
374 mapDs mk_arg (arg_tys `zip` dataConFieldLabels con_id) `thenDs` \ con_args ->
376 mkAppDs con_expr' [] con_args
378 -- The "con_expr'" is simply an application of the constructor Id
379 -- to types and (perhaps) dictionaries. This boring little
380 -- function gets the constructor out.
381 get_con_id (App fun _) = get_con_id fun
382 get_con_id (Var con) = con
385 Record update is a little harder. Suppose we have the decl:
387 data T = T1 {op1, op2, op3 :: Int}
388 | T2 {op4, op1 :: Int}
391 Then we translate as follows:
397 T1 op1 _ op3 -> T1 op1 op2 op3
398 T2 op4 _ -> T2 op4 op2
399 other -> recUpdError "M.lhs/230"
401 It's important that we use the constructor Ids for T1, T2 etc on the
402 RHSs, and do not generate a Core Con directly, because the constructor
403 might do some argument-evaluation first; and may have to throw away some
407 dsExpr (RecordUpdOut record_expr dicts rbinds)
408 = dsExpr record_expr `thenDs` \ record_expr' ->
410 -- Desugar the rbinds, and generate let-bindings if
411 -- necessary so that we don't lose sharing
412 -- dsRbinds rbinds $ \ rbinds' ->
413 let rbinds' = panic "dsExpr:RecordUpdOut:rbinds'" in
415 record_ty = coreExprType record_expr'
416 (tycon, inst_tys, cons) = getAppDataTyCon record_ty
417 cons_to_upd = filter has_all_fields cons
419 -- initial_args are passed to every constructor
420 initial_args = map TyArg inst_tys ++ map VarArg dicts
422 mk_val_arg (field, arg_id)
423 = case [arg | (f, arg) <- rbinds', f==field] of
424 (arg:args) -> ASSERT(null args)
429 = newSysLocalsDs (dataConArgTys con inst_tys) `thenDs` \ arg_ids ->
431 val_args = map mk_val_arg (dataConFieldLabels con `zipEqual` arg_ids)
433 returnDs (con, arg_ids, mkGenApp (mkGenApp (Var con) initial_args) val_args)
436 | length cons_to_upd == length cons
439 = newSysLocalDs record_ty `thenDs` \ deflt_id ->
440 mkErrorAppDs rEC_UPD_ERROR_ID record_ty "" `thenDs` \ err ->
441 returnDs (BindDefault deflt_id err)
443 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
444 mk_default `thenDs` \ deflt ->
446 returnDs (Case record_expr' (AlgAlts alts deflt))
449 has_all_fields :: Id -> Bool
450 has_all_fields con_id
453 con_fields = dataConFieldLabels con_id
454 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
457 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.
463 dsExpr (DictLam dictvars expr)
464 = dsExpr expr `thenDs` \ core_expr ->
465 returnDs( mkValLam dictvars core_expr )
469 dsExpr expr@(DictApp e dicts) -- becomes a curried application
473 @SingleDicts@ become @Locals@; @Dicts@ turn into tuples, unless
475 @ClassDictLam dictvars methods expr@ is ``the opposite'':
477 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
480 dsExpr (SingleDict dict) -- just a local
481 = lookupEnvWithDefaultDs dict (Var dict)
483 dsExpr (Dictionary dicts methods)
484 = -- hey, these things may have been substituted away...
485 zipWithDs lookupEnvWithDefaultDs
486 dicts_and_methods dicts_and_methods_exprs
487 `thenDs` \ core_d_and_ms ->
489 (case num_of_d_and_ms of
490 0 -> returnDs cocon_unit -- unit
492 1 -> returnDs (head core_d_and_ms) -- just a single Id
495 mkConDs (mkTupleCon num_of_d_and_ms)
496 (map coreExprType core_d_and_ms)
500 dicts_and_methods = dicts ++ methods
501 dicts_and_methods_exprs = map Var dicts_and_methods
502 num_of_d_and_ms = length dicts_and_methods
504 dsExpr (ClassDictLam dicts methods expr)
505 = dsExpr expr `thenDs` \ core_expr ->
506 case num_of_d_and_ms of
507 0 -> newSysLocalDs unitTy `thenDs` \ new_x ->
508 returnDs (mkValLam [new_x] core_expr)
511 returnDs (mkValLam dicts_and_methods core_expr)
514 newSysLocalDs tuple_ty `thenDs` \ new_x ->
516 Lam (ValBinder new_x)
519 [(tuple_con, dicts_and_methods, core_expr)]
522 num_of_d_and_ms = length dicts + length methods
523 dicts_and_methods = dicts ++ methods
524 tuple_ty = mkTupleTy num_of_d_and_ms (map idType dicts_and_methods)
525 tuple_con = mkTupleCon num_of_d_and_ms
528 -- HsSyn constructs that just shouldn't be here:
529 dsExpr (HsDo _ _) = panic "dsExpr:HsDo"
530 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
531 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
532 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
535 cocon_unit = mkCon (mkTupleCon 0) [] [] [] -- out here to avoid CAF (sigh)
536 out_of_range_msg -- ditto
537 = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
540 %--------------------------------------------------------------------
542 @(dsApp e [t_1,..,t_n, e_1,..,e_n])@ returns something with the same
545 e t_1 ... t_n e_1 .. e_n
548 We're doing all this so we can saturate constructors (as painlessly as
552 type DsCoreArg = GenCoreArg CoreExpr{-NB!-} TyVar UVar
554 dsApp :: TypecheckedHsExpr -- expr to desugar
555 -> [DsCoreArg] -- accumulated ty/val args: NB:
556 -> DsM CoreExpr -- final result
558 dsApp (HsApp e1 e2) args
559 = dsExpr e2 `thenDs` \ core_e2 ->
560 dsApp e1 (VarArg core_e2 : args)
562 dsApp (OpApp e1 op e2) args
563 = dsExpr e1 `thenDs` \ core_e1 ->
564 dsExpr e2 `thenDs` \ core_e2 ->
565 dsApp op (VarArg core_e1 : VarArg core_e2 : args)
567 dsApp (DictApp expr dicts) args
568 = -- now, those dicts may have been substituted away...
569 zipWithDs lookupEnvWithDefaultDs dicts (map Var dicts)
570 `thenDs` \ core_dicts ->
571 dsApp expr (map VarArg core_dicts ++ args)
573 dsApp (TyApp expr tys) args
574 = dsApp expr (map TyArg tys ++ args)
576 -- we might should look out for SectionLs, etc., here, but we don't
579 = lookupEnvDs v `thenDs` \ maybe_expr ->
581 Just expr -> apply_to_args expr args
583 Nothing -> -- we're only saturating constructors and PrimOps
584 case getIdUnfolding v of
585 GenForm _ _ the_unfolding EssentialUnfolding
586 -> do_unfold nullTyVarEnv nullIdEnv (unTagBinders the_unfolding) args
588 _ -> apply_to_args (Var v) args
591 dsApp anything_else args
592 = dsExpr anything_else `thenDs` \ core_expr ->
593 apply_to_args core_expr args
595 -- a DsM version of mkGenApp:
596 apply_to_args :: CoreExpr -> [DsCoreArg] -> DsM CoreExpr
598 apply_to_args fun args
600 (ty_args, val_args) = foldr sep ([],[]) args
602 mkAppDs fun ty_args val_args
604 sep a@(LitArg l) (tys,vals) = (tys, (Lit l):vals)
605 sep a@(VarArg e) (tys,vals) = (tys, e:vals)
606 sep a@(TyArg ty) (tys,vals) = (ty:tys, vals)
607 sep a@(UsageArg _) _ = panic "DsExpr:apply_to_args:UsageArg"
612 dsRbinds :: TypecheckedRecordBinds -- The field bindings supplied
613 -> ([(Id, CoreArg)] -> DsM CoreExpr) -- A continuation taking the field
614 -- bindings with atomic rhss
615 -> DsM CoreExpr -- The result of the continuation,
616 -- wrapped in suitable Lets
618 dsRbinds [] continue_with
621 dsRbinds ((sel_id, rhs, pun_flag) : rbinds) continue_with
622 = dsExpr rhs `thenDs` \ rhs' ->
623 dsExprToAtom rhs' $ \ rhs_atom ->
624 dsRbinds rbinds $ \ rbinds' ->
625 continue_with ((panic "dsRbinds:field_label?"{-sel_id-}, rhs_atom) : rbinds')
629 do_unfold ty_env val_env (Lam (TyBinder tyvar) body) (TyArg ty : args)
630 = do_unfold (addOneToTyVarEnv ty_env tyvar ty) val_env body args
632 do_unfold ty_env val_env (Lam (ValBinder binder) body) (VarArg expr : args)
633 = dsExprToAtom expr $ \ arg_atom ->
635 (addOneToIdEnv val_env binder (argToExpr arg_atom))
638 do_unfold ty_env val_env body args
639 = -- Clone the remaining part of the template
640 uniqSMtoDsM (substCoreExpr val_env ty_env body) `thenDs` \ body' ->
642 -- Apply result to remaining arguments
643 apply_to_args body' args