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(..) )
20 import DsCCall ( dsCCall )
21 import DsListComp ( dsListComp )
22 import DsUtils ( mkAppDs, mkConDs, mkPrimDs, dsExprToAtom )
23 import Match ( matchWrapper )
25 import CoreUnfold ( UnfoldingDetails(..), UnfoldingGuidance(..),
27 import CoreUtils ( coreExprType, substCoreExpr, argToExpr,
28 mkCoreIfThenElse, unTagBinders )
29 import CostCentre ( mkUserCC )
30 import Id ( mkTupleCon, idType, nullIdEnv, addOneToIdEnv,
32 import Literal ( mkMachInt, Literal(..) )
33 import MagicUFs ( MagicUnfoldingFun )
34 import PprStyle ( PprStyle(..) )
35 import PprType ( GenType, GenTyVar )
36 import PrelInfo ( mkTupleTy, unitTy, nilDataCon, consDataCon,
38 import Pretty ( ppShow )
39 import Type ( splitSigmaTy )
40 import TyVar ( nullTyVarEnv, addOneToTyVarEnv, GenTyVar )
41 import Unique ( Unique )
42 import Usage ( UVar(..) )
45 primRepFromType = panic "DsExpr.primRepFromType"
46 maybeBoxedPrimType = panic "DsExpr.maybeBoxedPrimType"
47 splitTyArgs = panic "DsExpr.splitTyArgs"
49 mk_nil_con ty = mkCon nilDataCon [] [ty] [] -- micro utility...
52 The funny business to do with variables is that we look them up in the
53 Id-to-Id and Id-to-Id maps that the monadery is carrying
54 around; if we get hits, we use the value accordingly.
56 %************************************************************************
58 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
60 %************************************************************************
63 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
65 dsExpr (HsVar var) = dsApp (HsVar var) []
68 %************************************************************************
70 \subsection[DsExpr-literals]{Literals}
72 %************************************************************************
74 We give int/float literals type Integer and Rational, respectively.
75 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
78 ToDo: put in range checks for when converting "i"
79 (or should that be in the typechecker?)
81 For numeric literals, we try to detect there use at a standard type
82 (Int, Float, etc.) are directly put in the right constructor.
83 [NB: down with the @App@ conversion.]
84 Otherwise, we punt, putting in a "NoRep" Core literal (where the
85 representation decisions are delayed)...
87 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
90 dsExpr (HsLitOut (HsString s) _)
92 = returnDs (mk_nil_con charTy)
96 the_char = mkCon charDataCon [] [] [LitArg (MachChar (_HEAD_ s))]
97 the_nil = mk_nil_con charTy
99 mkConDs consDataCon [charTy] [the_char, the_nil]
101 -- "_" => build (\ c n -> c 'c' n) -- LATER
103 -- "str" ==> build (\ c n -> foldr charTy T c n "str")
106 dsExpr (HsLitOut (HsString str) _) =
107 newTyVarsDs [alphaTyVar] `thenDs` \ [new_tyvar] ->
109 new_ty = mkTyVarTy new_tyvar
112 charTy `mkFunTy` (new_ty `mkFunTy` new_ty),
114 mkForallTy [alphaTyVar]
115 ((charTy `mkFunTy` (alphaTy `mkFunTy` alphaTy))
116 `mkFunTy` (alphaTy `mkFunTy` alphaTy))
117 ] `thenDs` \ [c,n,g] ->
118 returnDs (mkBuild charTy new_tyvar c n g (
120 (CoTyApp (CoTyApp (Var foldrId) charTy) new_ty) *** ensure non-prim type ***
121 [VarArg c,VarArg n,LitArg (NoRepStr str)]))
124 -- otherwise, leave it as a NoRepStr;
125 -- the Core-to-STG pass will wrap it in an application of "unpackCStringId".
127 dsExpr (HsLitOut (HsString str) _)
128 = returnDs (Lit (NoRepStr str))
130 dsExpr (HsLitOut (HsLitLit s) ty)
131 = returnDs ( mkCon data_con [] [] [LitArg (MachLitLit s kind)] )
134 = case (maybeBoxedPrimType ty) of
136 -> error ("ERROR: ``literal-literal'' not a single-constructor type: "++ _UNPK_ s ++"; type: "++(ppShow 80 (ppr PprDebug ty)))
137 Just (boxing_data_con, prim_ty)
138 -> (boxing_data_con, primRepFromType prim_ty)
140 dsExpr (HsLitOut (HsInt i) _)
141 = returnDs (Lit (NoRepInteger i))
143 dsExpr (HsLitOut (HsFrac r) _)
144 = returnDs (Lit (NoRepRational r))
146 -- others where we know what to do:
148 dsExpr (HsLitOut (HsIntPrim i) _)
149 = if (i >= toInteger minInt && i <= toInteger maxInt) then
150 returnDs (Lit (mkMachInt i))
152 error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
154 dsExpr (HsLitOut (HsFloatPrim f) _)
155 = returnDs (Lit (MachFloat f))
156 -- ToDo: range checking needed!
158 dsExpr (HsLitOut (HsDoublePrim d) _)
159 = returnDs (Lit (MachDouble d))
160 -- ToDo: range checking needed!
162 dsExpr (HsLitOut (HsChar c) _)
163 = returnDs ( mkCon charDataCon [] [] [LitArg (MachChar c)] )
165 dsExpr (HsLitOut (HsCharPrim c) _)
166 = returnDs (Lit (MachChar c))
168 dsExpr (HsLitOut (HsStringPrim s) _)
169 = returnDs (Lit (MachStr s))
171 -- end of literals magic. --
173 dsExpr expr@(HsLam a_Match)
175 error_msg = "%L" --> "pattern-matching failed in lambda"
177 matchWrapper LambdaMatch [a_Match] error_msg `thenDs` \ (binders, matching_code) ->
178 returnDs ( mkValLam binders matching_code )
180 dsExpr expr@(HsApp e1 e2) = dsApp expr []
181 dsExpr expr@(OpApp e1 op e2) = dsApp expr []
184 Operator sections. At first it looks as if we can convert
193 But no! expr might be a redex, and we can lose laziness badly this
198 for example. So we convert instead to
200 let y = expr in \x -> op y x
202 If \tr{expr} is actually just a variable, say, then the simplifier
206 dsExpr (SectionL expr op)
207 = dsExpr op `thenDs` \ core_op ->
208 dsExpr expr `thenDs` \ core_expr ->
209 dsExprToAtom core_expr $ \ y_atom ->
211 -- for the type of x, we need the type of op's 2nd argument
213 x_ty = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
214 case (splitTyArgs tau_ty) of {
215 ((_:arg2_ty:_), _) -> arg2_ty;
216 _ -> panic "dsExpr:SectionL:arg 2 ty"
219 newSysLocalDs x_ty `thenDs` \ x_id ->
220 returnDs (mkValLam [x_id] (core_op `App` y_atom `App` VarArg x_id))
222 -- dsExpr (SectionR op expr) -- \ x -> op x expr
223 dsExpr (SectionR op expr)
224 = dsExpr op `thenDs` \ core_op ->
225 dsExpr expr `thenDs` \ core_expr ->
226 dsExprToAtom core_expr $ \ y_atom ->
228 -- for the type of x, we need the type of op's 1st argument
230 x_ty = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
231 case (splitTyArgs tau_ty) of {
232 ((arg1_ty:_), _) -> arg1_ty;
233 _ -> panic "dsExpr:SectionR:arg 1 ty"
236 newSysLocalDs x_ty `thenDs` \ x_id ->
237 returnDs (mkValLam [x_id] (core_op `App` VarArg x_id `App` y_atom))
239 dsExpr (CCall label args may_gc is_asm result_ty)
240 = mapDs dsExpr args `thenDs` \ core_args ->
241 dsCCall label core_args may_gc is_asm result_ty
242 -- dsCCall does all the unboxification, etc.
244 dsExpr (HsSCC cc expr)
245 = dsExpr expr `thenDs` \ core_expr ->
246 getModuleAndGroupDs `thenDs` \ (mod_name, group_name) ->
247 returnDs ( SCC (mkUserCC cc mod_name group_name) core_expr)
249 dsExpr expr@(HsCase discrim matches src_loc)
250 = putSrcLocDs src_loc $
251 dsExpr discrim `thenDs` \ core_discrim ->
253 error_msg = "%C" --> "pattern-matching failed in case"
255 matchWrapper CaseMatch matches error_msg `thenDs` \ ([discrim_var], matching_code) ->
256 returnDs ( mkCoLetAny (NonRec discrim_var core_discrim) matching_code )
258 dsExpr (ListComp expr quals)
259 = dsExpr expr `thenDs` \ core_expr ->
260 dsListComp core_expr quals
262 dsExpr (HsLet binds expr)
263 = dsBinds binds `thenDs` \ core_binds ->
264 dsExpr expr `thenDs` \ core_expr ->
265 returnDs ( mkCoLetsAny core_binds core_expr )
267 dsExpr (HsDoOut stmts m_id mz_id src_loc)
268 = putSrcLocDs src_loc $
269 panic "dsExpr:HsDoOut"
271 dsExpr (ExplicitListOut ty xs)
273 [] -> returnDs (mk_nil_con ty)
275 dsExpr y `thenDs` \ core_hd ->
276 dsExpr (ExplicitListOut ty ys) `thenDs` \ core_tl ->
277 mkConDs consDataCon [ty] [core_hd, core_tl]
279 dsExpr (ExplicitTuple expr_list)
280 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
281 mkConDs (mkTupleCon (length expr_list))
282 (map coreExprType core_exprs)
285 dsExpr (RecordCon con rbinds) = panic "dsExpr:RecordCon"
286 dsExpr (RecordUpd aexp rbinds) = panic "dsExpr:RecordUpd"
288 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
289 = putSrcLocDs src_loc $
290 dsExpr guard_expr `thenDs` \ core_guard ->
291 dsExpr then_expr `thenDs` \ core_then ->
292 dsExpr else_expr `thenDs` \ core_else ->
293 returnDs (mkCoreIfThenElse core_guard core_then core_else)
295 dsExpr (ArithSeqOut expr (From from))
296 = dsExpr expr `thenDs` \ expr2 ->
297 dsExpr from `thenDs` \ from2 ->
298 mkAppDs expr2 [] [from2]
300 dsExpr (ArithSeqOut expr (FromTo from two))
301 = dsExpr expr `thenDs` \ expr2 ->
302 dsExpr from `thenDs` \ from2 ->
303 dsExpr two `thenDs` \ two2 ->
304 mkAppDs expr2 [] [from2, two2]
306 dsExpr (ArithSeqOut expr (FromThen from thn))
307 = dsExpr expr `thenDs` \ expr2 ->
308 dsExpr from `thenDs` \ from2 ->
309 dsExpr thn `thenDs` \ thn2 ->
310 mkAppDs expr2 [] [from2, thn2]
312 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
313 = dsExpr expr `thenDs` \ expr2 ->
314 dsExpr from `thenDs` \ from2 ->
315 dsExpr thn `thenDs` \ thn2 ->
316 dsExpr two `thenDs` \ two2 ->
317 mkAppDs expr2 [] [from2, thn2, two2]
321 dsExpr (TyLam tyvars expr)
322 = dsExpr expr `thenDs` \ core_expr ->
323 returnDs (mkTyLam tyvars core_expr)
325 dsExpr expr@(TyApp e tys) = dsApp expr []
328 @DictLam@ and @DictApp@ turn into the regular old things.
329 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
330 complicated; reminiscent of fully-applied constructors.
332 dsExpr (DictLam dictvars expr)
333 = dsExpr expr `thenDs` \ core_expr ->
334 returnDs( mkValLam dictvars core_expr )
338 dsExpr expr@(DictApp e dicts) -- becomes a curried application
342 @SingleDicts@ become @Locals@; @Dicts@ turn into tuples, unless
344 @ClassDictLam dictvars methods expr@ is ``the opposite'':
346 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
349 dsExpr (SingleDict dict) -- just a local
350 = lookupEnvWithDefaultDs dict (Var dict)
352 dsExpr (Dictionary dicts methods)
353 = -- hey, these things may have been substituted away...
354 zipWithDs lookupEnvWithDefaultDs
355 dicts_and_methods dicts_and_methods_exprs
356 `thenDs` \ core_d_and_ms ->
358 (case num_of_d_and_ms of
359 0 -> returnDs cocon_unit -- unit
361 1 -> returnDs (head core_d_and_ms) -- just a single Id
364 mkConDs (mkTupleCon num_of_d_and_ms)
365 (map coreExprType core_d_and_ms)
369 dicts_and_methods = dicts ++ methods
370 dicts_and_methods_exprs = map Var dicts_and_methods
371 num_of_d_and_ms = length dicts_and_methods
373 dsExpr (ClassDictLam dicts methods expr)
374 = dsExpr expr `thenDs` \ core_expr ->
375 case num_of_d_and_ms of
376 0 -> newSysLocalDs unitTy `thenDs` \ new_x ->
377 returnDs (mkValLam [new_x] core_expr)
380 returnDs (mkValLam dicts_and_methods core_expr)
383 newSysLocalDs tuple_ty `thenDs` \ new_x ->
385 Lam (ValBinder new_x)
388 [(tuple_con, dicts_and_methods, core_expr)]
391 num_of_d_and_ms = length dicts + length methods
392 dicts_and_methods = dicts ++ methods
393 tuple_ty = mkTupleTy num_of_d_and_ms (map idType dicts_and_methods)
394 tuple_con = mkTupleCon num_of_d_and_ms
397 -- HsSyn constructs that just shouldn't be here:
398 dsExpr (HsDo _ _) = panic "dsExpr:HsDo"
399 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
400 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
401 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
404 cocon_unit = mkCon (mkTupleCon 0) [] [] [] -- out here to avoid CAF (sigh)
405 out_of_range_msg -- ditto
406 = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
409 %--------------------------------------------------------------------
411 @(dsApp e [t_1,..,t_n, e_1,..,e_n])@ returns something with the same
414 e t_1 ... t_n e_1 .. e_n
417 We're doing all this so we can saturate constructors (as painlessly as
421 type DsCoreArg = GenCoreArg CoreExpr{-NB!-} TyVar UVar
423 dsApp :: TypecheckedHsExpr -- expr to desugar
424 -> [DsCoreArg] -- accumulated ty/val args: NB:
425 -> DsM CoreExpr -- final result
427 dsApp (HsApp e1 e2) args
428 = dsExpr e2 `thenDs` \ core_e2 ->
429 dsApp e1 (VarArg core_e2 : args)
431 dsApp (OpApp e1 op e2) args
432 = dsExpr e1 `thenDs` \ core_e1 ->
433 dsExpr e2 `thenDs` \ core_e2 ->
434 dsApp op (VarArg core_e1 : VarArg core_e2 : args)
436 dsApp (DictApp expr dicts) args
437 = -- now, those dicts may have been substituted away...
438 zipWithDs lookupEnvWithDefaultDs dicts (map Var dicts)
439 `thenDs` \ core_dicts ->
440 dsApp expr (map VarArg core_dicts ++ args)
442 dsApp (TyApp expr tys) args
443 = dsApp expr (map TyArg tys ++ args)
445 -- we might should look out for SectionLs, etc., here, but we don't
448 = lookupEnvDs v `thenDs` \ maybe_expr ->
450 Just expr -> apply_to_args expr args
452 Nothing -> -- we're only saturating constructors and PrimOps
453 case getIdUnfolding v of
454 GenForm _ _ the_unfolding EssentialUnfolding
455 -> do_unfold nullTyVarEnv nullIdEnv (unTagBinders the_unfolding) args
457 _ -> apply_to_args (Var v) args
460 dsApp anything_else args
461 = dsExpr anything_else `thenDs` \ core_expr ->
462 apply_to_args core_expr args
464 -- a DsM version of mkGenApp:
465 apply_to_args :: CoreExpr -> [DsCoreArg] -> DsM CoreExpr
467 apply_to_args fun args
469 (ty_args, val_args) = foldr sep ([],[]) args
471 mkAppDs fun ty_args val_args
473 sep a@(LitArg l) (tys,vals) = (tys, (Lit l):vals)
474 sep a@(VarArg e) (tys,vals) = (tys, e:vals)
475 sep a@(TyArg ty) (tys,vals) = (ty:tys, vals)
476 sep a@(UsageArg _) _ = panic "DsExpr:apply_to_args:UsageArg"
480 do_unfold ty_env val_env (Lam (TyBinder tyvar) body) (TyArg ty : args)
481 = do_unfold (addOneToTyVarEnv ty_env tyvar ty) val_env body args
483 do_unfold ty_env val_env (Lam (ValBinder binder) body) (VarArg expr : args)
484 = dsExprToAtom expr $ \ arg_atom ->
486 (addOneToIdEnv val_env binder (argToExpr arg_atom))
489 do_unfold ty_env val_env body args
490 = -- Clone the remaining part of the template
491 uniqSMtoDsM (substCoreExpr val_env ty_env body) `thenDs` \ body' ->
493 -- Apply result to remaining arguments
494 apply_to_args body' args