2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[DsExpr]{Matching expressions (Exprs)}
7 module DsExpr ( dsExpr, dsLet ) where
9 #include "HsVersions.h"
12 import HsSyn ( failureFreePat,
13 HsExpr(..), OutPat(..), HsLit(..), ArithSeqInfo(..),
14 Stmt(..), StmtCtxt(..), Match(..), HsBinds(..), MonoBinds(..),
17 import TcHsSyn ( TypecheckedHsExpr, TypecheckedHsBinds,
25 import DsBinds ( dsMonoBinds )
26 import DsGRHSs ( dsGuarded )
27 import DsCCall ( dsCCall )
28 import DsListComp ( dsListComp )
29 import DsUtils ( mkErrorAppDs )
30 import Match ( matchWrapper, matchSimply )
32 import CoreUtils ( coreExprType )
33 import CostCentre ( mkUserCC )
34 import FieldLabel ( FieldLabel )
35 import Id ( Id, idType, recordSelectorFieldLabel )
36 import Const ( Con(..) )
37 import DataCon ( DataCon, dataConId, dataConTyCon, dataConArgTys, dataConFieldLabels )
38 import Const ( mkMachInt, Literal(..) )
39 import PrelVals ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID )
40 import TyCon ( isNewTyCon )
41 import DataCon ( isExistentialDataCon )
42 import Type ( splitFunTys, mkTyConApp,
43 splitAlgTyConApp, splitTyConApp_maybe,
44 splitAppTy, isUnLiftedType, Type
46 import TysWiredIn ( tupleCon, unboxedTupleCon,
47 consDataCon, listTyCon, mkListTy,
48 charDataCon, charTy, stringTy
50 import BasicTypes ( RecFlag(..) )
51 import Maybes ( maybeToBool )
52 import Util ( zipEqual, zipWithEqual )
57 %************************************************************************
61 %************************************************************************
63 @dsLet@ is a match-result transformer, taking the MatchResult for the body
64 and transforming it into one for the let-bindings enclosing the body.
66 This may seem a bit odd, but (source) let bindings can contain unboxed
71 This must be transformed to a case expression and, if the type has
72 more than one constructor, may fail.
75 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
80 dsLet (ThenBinds b1 b2) body
81 = dsLet b2 body `thenDs` \ body' ->
84 -- Special case for bindings which bind unlifted variables
85 dsLet (MonoBind (AbsBinds [] [] binder_triples (PatMonoBind pat grhss loc)) sigs is_rec) body
86 | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
87 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
89 dsGuarded grhss `thenDs` \ rhs ->
91 body' = foldr bind body binder_triples
92 bind (tyvars, g, l) body = ASSERT( null tyvars )
93 bindNonRec g (Var l) body
95 mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat)) `thenDs` \ error_expr ->
96 matchSimply rhs PatBindMatch pat body' error_expr
98 result_ty = coreExprType body
100 -- Ordinary case for bindings
101 dsLet (MonoBind binds sigs is_rec) body
102 = dsMonoBinds False binds [] `thenDs` \ prs ->
104 Recursive -> returnDs (Let (Rec prs) body)
105 NonRecursive -> returnDs (foldr mk_let body prs)
107 mk_let (bndr,rhs) body = Let (NonRec bndr rhs) body
110 %************************************************************************
112 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
114 %************************************************************************
117 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
119 dsExpr e@(HsVar var) = returnDs (Var var)
122 %************************************************************************
124 \subsection[DsExpr-literals]{Literals}
126 %************************************************************************
128 We give int/float literals type Integer and Rational, respectively.
129 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
132 ToDo: put in range checks for when converting "i"
133 (or should that be in the typechecker?)
135 For numeric literals, we try to detect there use at a standard type
136 (Int, Float, etc.) are directly put in the right constructor.
137 [NB: down with the @App@ conversion.]
138 Otherwise, we punt, putting in a "NoRep" Core literal (where the
139 representation decisions are delayed)...
141 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
144 dsExpr (HsLitOut (HsString s) _)
146 = returnDs (mkNilExpr charTy)
150 the_char = mkConApp charDataCon [mkLit (MachChar (_HEAD_ s))]
151 the_nil = mkNilExpr charTy
152 the_cons = mkConApp consDataCon [Type charTy, the_char, the_nil]
157 -- "_" => build (\ c n -> c 'c' n) -- LATER
159 -- "str" ==> build (\ c n -> foldr charTy T c n "str")
162 dsExpr (HsLitOut (HsString str) _)
163 = newTyVarsDs [alphaTyVar] `thenDs` \ [new_tyvar] ->
165 new_ty = mkTyVarTy new_tyvar
168 charTy `mkFunTy` (new_ty `mkFunTy` new_ty),
170 mkForallTy [alphaTyVar]
171 ((charTy `mkFunTy` (alphaTy `mkFunTy` alphaTy))
172 `mkFunTy` (alphaTy `mkFunTy` alphaTy))
173 ] `thenDs` \ [c,n,g] ->
174 returnDs (mkBuild charTy new_tyvar c n g (
176 (CoTyApp (CoTyApp (Var foldrId) charTy) new_ty) *** ensure non-prim type ***
177 [VarArg c,VarArg n,LitArg (NoRepStr str)]))
180 -- otherwise, leave it as a NoRepStr;
181 -- the Core-to-STG pass will wrap it in an application of "unpackCStringId".
183 dsExpr (HsLitOut (HsString str) _)
184 = returnDs (mkLit (NoRepStr str stringTy))
186 dsExpr (HsLitOut (HsLitLit str) ty)
187 = returnDs ( mkConApp data_con [mkLit (MachLitLit str prim_ty)] )
190 = case (maybeBoxedPrimType ty) of
191 Just (boxing_data_con, prim_ty) -> (boxing_data_con, prim_ty)
193 -> pprPanic "ERROR: ``literal-literal'' not a single-constructor type: "
194 (hcat [ptext str, text "; type: ", ppr ty])
196 dsExpr (HsLitOut (HsInt i) ty)
197 = returnDs (mkLit (NoRepInteger i ty))
199 dsExpr (HsLitOut (HsFrac r) ty)
200 = returnDs (mkLit (NoRepRational r ty))
202 -- others where we know what to do:
204 dsExpr (HsLitOut (HsIntPrim i) _)
205 | (i >= toInteger minInt && i <= toInteger maxInt)
206 = returnDs (mkLit (mkMachInt i))
208 = error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
210 dsExpr (HsLitOut (HsFloatPrim f) _)
211 = returnDs (mkLit (MachFloat f))
212 -- ToDo: range checking needed!
214 dsExpr (HsLitOut (HsDoublePrim d) _)
215 = returnDs (mkLit (MachDouble d))
216 -- ToDo: range checking needed!
218 dsExpr (HsLitOut (HsChar c) _)
219 = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
221 dsExpr (HsLitOut (HsCharPrim c) _)
222 = returnDs (mkLit (MachChar c))
224 dsExpr (HsLitOut (HsStringPrim s) _)
225 = returnDs (mkLit (MachStr s))
227 -- end of literals magic. --
229 dsExpr expr@(HsLam a_Match)
230 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
231 returnDs (mkLams binders matching_code)
233 dsExpr expr@(HsApp fun arg)
234 = dsExpr fun `thenDs` \ core_fun ->
235 dsExpr arg `thenDs` \ core_arg ->
236 returnDs (core_fun `App` core_arg)
240 Operator sections. At first it looks as if we can convert
249 But no! expr might be a redex, and we can lose laziness badly this
254 for example. So we convert instead to
256 let y = expr in \x -> op y x
258 If \tr{expr} is actually just a variable, say, then the simplifier
262 dsExpr (OpApp e1 op _ e2)
263 = dsExpr op `thenDs` \ core_op ->
264 -- for the type of y, we need the type of op's 2nd argument
266 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
268 dsExpr e1 `thenDs` \ x_core ->
269 dsExpr e2 `thenDs` \ y_core ->
270 returnDs (mkApps core_op [x_core, y_core])
272 dsExpr (SectionL expr op)
273 = dsExpr op `thenDs` \ core_op ->
274 -- for the type of y, we need the type of op's 2nd argument
276 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
278 dsExpr expr `thenDs` \ x_core ->
279 newSysLocalDs x_ty `thenDs` \ x_id ->
280 newSysLocalDs y_ty `thenDs` \ y_id ->
282 returnDs (bindNonRec x_id x_core $
283 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
285 -- dsExpr (SectionR op expr) -- \ x -> op x expr
286 dsExpr (SectionR op expr)
287 = dsExpr op `thenDs` \ core_op ->
288 -- for the type of x, we need the type of op's 2nd argument
290 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
292 dsExpr expr `thenDs` \ y_core ->
293 newSysLocalDs x_ty `thenDs` \ x_id ->
294 newSysLocalDs y_ty `thenDs` \ y_id ->
296 returnDs (bindNonRec y_id y_core $
297 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
299 dsExpr (CCall label args may_gc is_asm result_ty)
300 = mapDs dsExpr args `thenDs` \ core_args ->
301 dsCCall label core_args may_gc is_asm result_ty
302 -- dsCCall does all the unboxification, etc.
304 dsExpr (HsSCC cc expr)
305 = dsExpr expr `thenDs` \ core_expr ->
306 getModuleAndGroupDs `thenDs` \ (mod_name, group_name) ->
307 returnDs (Note (SCC (mkUserCC cc mod_name group_name)) core_expr)
309 -- special case to handle unboxed tuple patterns
311 dsExpr (HsCase discrim matches@[Match _ [TuplePat ps boxed] _ _] src_loc)
313 = putSrcLocDs src_loc $
314 dsExpr discrim `thenDs` \ core_discrim ->
315 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
316 case matching_code of
317 Case (Var x) bndr alts | x == discrim_var ->
318 returnDs (Case core_discrim bndr alts)
319 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
321 dsExpr (HsCase discrim matches src_loc)
322 = putSrcLocDs src_loc $
323 dsExpr discrim `thenDs` \ core_discrim ->
324 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
325 returnDs (bindNonRec discrim_var core_discrim matching_code)
327 dsExpr (HsLet binds body)
328 = dsExpr body `thenDs` \ body' ->
331 dsExpr (HsDoOut do_or_lc stmts return_id then_id zero_id result_ty src_loc)
332 | maybeToBool maybe_list_comp
333 = -- Special case for list comprehensions
334 putSrcLocDs src_loc $
335 dsListComp stmts elt_ty
338 = putSrcLocDs src_loc $
339 dsDo do_or_lc stmts return_id then_id zero_id result_ty
342 = case (do_or_lc, splitTyConApp_maybe result_ty) of
343 (ListComp, Just (tycon, [elt_ty]))
347 -- We need the ListComp form to use deListComp (rather than the "do" form)
348 -- because the "return" in a do block is a call to "PrelBase.return", and
349 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
351 Just elt_ty = maybe_list_comp
353 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
354 = putSrcLocDs src_loc $
355 dsExpr guard_expr `thenDs` \ core_guard ->
356 dsExpr then_expr `thenDs` \ core_then ->
357 dsExpr else_expr `thenDs` \ core_else ->
358 returnDs (mkIfThenElse core_guard core_then core_else)
362 Type lambda and application
363 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
365 dsExpr (TyLam tyvars expr)
366 = dsExpr expr `thenDs` \ core_expr ->
367 returnDs (mkLams tyvars core_expr)
369 dsExpr (TyApp expr tys)
370 = dsExpr expr `thenDs` \ core_expr ->
371 returnDs (mkTyApps core_expr tys)
375 Various data construction things
376 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
378 dsExpr (ExplicitListOut ty xs)
381 list_ty = mkListTy ty
383 go [] = returnDs (mkNilExpr ty)
384 go (x:xs) = dsExpr x `thenDs` \ core_x ->
385 go xs `thenDs` \ core_xs ->
386 returnDs (mkConApp consDataCon [Type ty, core_x, core_xs])
388 dsExpr (ExplicitTuple expr_list boxed)
389 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
390 returnDs (mkConApp ((if boxed
392 else unboxedTupleCon) (length expr_list))
393 (map (Type . coreExprType) core_exprs ++ core_exprs))
395 dsExpr (HsCon con_id [ty] [arg])
397 = dsExpr arg `thenDs` \ arg' ->
398 returnDs (Note (Coerce result_ty (coreExprType arg')) arg')
400 result_ty = mkTyConApp tycon [ty]
401 tycon = dataConTyCon con_id
403 dsExpr (HsCon con_id tys args)
404 = mapDs dsExpr args `thenDs` \ args2 ->
405 returnDs (mkConApp con_id (map Type tys ++ args2))
407 dsExpr (ArithSeqOut expr (From from))
408 = dsExpr expr `thenDs` \ expr2 ->
409 dsExpr from `thenDs` \ from2 ->
410 returnDs (App expr2 from2)
412 dsExpr (ArithSeqOut expr (FromTo from two))
413 = dsExpr expr `thenDs` \ expr2 ->
414 dsExpr from `thenDs` \ from2 ->
415 dsExpr two `thenDs` \ two2 ->
416 returnDs (mkApps expr2 [from2, two2])
418 dsExpr (ArithSeqOut expr (FromThen from thn))
419 = dsExpr expr `thenDs` \ expr2 ->
420 dsExpr from `thenDs` \ from2 ->
421 dsExpr thn `thenDs` \ thn2 ->
422 returnDs (mkApps expr2 [from2, thn2])
424 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
425 = dsExpr expr `thenDs` \ expr2 ->
426 dsExpr from `thenDs` \ from2 ->
427 dsExpr thn `thenDs` \ thn2 ->
428 dsExpr two `thenDs` \ two2 ->
429 returnDs (mkApps expr2 [from2, thn2, two2])
432 Record construction and update
433 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
434 For record construction we do this (assuming T has three arguments)
438 let err = /\a -> recConErr a
439 T (recConErr t1 "M.lhs/230/op1")
441 (recConErr t1 "M.lhs/230/op3")
443 recConErr then converts its arugment string into a proper message
444 before printing it as
446 M.lhs, line 230: missing field op1 was evaluated
450 dsExpr (RecordConOut data_con con_expr rbinds)
451 = dsExpr con_expr `thenDs` \ con_expr' ->
453 (arg_tys, _) = splitFunTys (coreExprType con_expr')
456 = case [rhs | (sel_id,rhs,_) <- rbinds,
457 lbl == recordSelectorFieldLabel sel_id] of
458 (rhs:rhss) -> ASSERT( null rhss )
460 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
462 mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys (dataConFieldLabels data_con)) `thenDs` \ con_args ->
463 returnDs (mkApps con_expr' con_args)
466 Record update is a little harder. Suppose we have the decl:
468 data T = T1 {op1, op2, op3 :: Int}
469 | T2 {op4, op2 :: Int}
472 Then we translate as follows:
478 T1 op1 _ op3 -> T1 op1 op2 op3
479 T2 op4 _ -> T2 op4 op2
480 other -> recUpdError "M.lhs/230"
482 It's important that we use the constructor Ids for T1, T2 etc on the
483 RHSs, and do not generate a Core Con directly, because the constructor
484 might do some argument-evaluation first; and may have to throw away some
488 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
489 = dsExpr record_expr `thenDs` \ record_expr' ->
491 -- Desugar the rbinds, and generate let-bindings if
492 -- necessary so that we don't lose sharing
495 ds_rbind (sel_id, rhs, pun_flag)
496 = dsExpr rhs `thenDs` \ rhs' ->
497 returnDs (recordSelectorFieldLabel sel_id, rhs')
499 mapDs ds_rbind rbinds `thenDs` \ rbinds' ->
501 record_in_ty = coreExprType record_expr'
502 (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
503 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
504 cons_to_upd = filter has_all_fields cons
506 -- initial_args are passed to every constructor
507 initial_args = map Type out_inst_tys ++ map Var dicts
509 mk_val_arg field old_arg_id
510 = case [rhs | (f, rhs) <- rbinds', field == f] of
511 (rhs:rest) -> ASSERT(null rest) rhs
515 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
517 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
518 (dataConFieldLabels con) arg_ids
519 rhs = mkApps (mkApps (Var (dataConId con)) initial_args) val_args
521 returnDs (DataCon con, arg_ids, rhs)
524 | length cons_to_upd == length cons
527 = mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty "" `thenDs` \ err ->
528 returnDs [(DEFAULT, [], err)]
530 -- Record stuff doesn't work for existentials
531 ASSERT( all (not . isExistentialDataCon) cons )
533 newSysLocalDs record_in_ty `thenDs` \ case_bndr ->
534 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
535 mk_default `thenDs` \ deflt ->
537 returnDs (Case record_expr' case_bndr (alts ++ deflt))
539 has_all_fields :: DataCon -> Bool
540 has_all_fields con_id
543 con_fields = dataConFieldLabels con_id
544 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
547 Dictionary lambda and application
548 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
549 @DictLam@ and @DictApp@ turn into the regular old things.
550 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
551 complicated; reminiscent of fully-applied constructors.
553 dsExpr (DictLam dictvars expr)
554 = dsExpr expr `thenDs` \ core_expr ->
555 returnDs (mkLams dictvars core_expr)
559 dsExpr (DictApp expr dicts) -- becomes a curried application
560 = dsExpr expr `thenDs` \ core_expr ->
561 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
568 -- HsSyn constructs that just shouldn't be here:
569 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
570 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
571 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
572 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
575 out_of_range_msg -- ditto
576 = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
579 %--------------------------------------------------------------------
581 Basically does the translation given in the Haskell~1.3 report:
586 -> Id -- id for: return m
587 -> Id -- id for: (>>=) m
588 -> Id -- id for: zero m
589 -> Type -- Element type; the whole expression has type (m t)
592 dsDo do_or_lc stmts return_id then_id zero_id result_ty
594 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
597 = dsExpr expr `thenDs` \ expr2 ->
598 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
600 go (GuardStmt expr locn : stmts)
601 = do_expr expr locn `thenDs` \ expr2 ->
602 go stmts `thenDs` \ rest ->
603 returnDs (mkIfThenElse expr2 rest (App (Var zero_id) (Type b_ty)))
605 go (ExprStmt expr locn : stmts)
606 = do_expr expr locn `thenDs` \ expr2 ->
608 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
613 go stmts `thenDs` \ rest ->
614 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
615 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
616 Lam ignored_result_id rest])
618 go (LetStmt binds : stmts )
619 = go stmts `thenDs` \ rest ->
622 go (BindStmt pat expr locn : stmts)
624 dsExpr expr `thenDs` \ expr2 ->
626 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
627 zero_expr = TyApp (HsVar zero_id) [b_ty]
628 main_match = mkSimpleMatch [pat] (HsDoOut do_or_lc stmts return_id then_id zero_id result_ty locn)
629 (Just result_ty) locn
631 = if failureFreePat pat
633 else [main_match, mkSimpleMatch [WildPat a_ty] zero_expr (Just result_ty) locn]
635 matchWrapper DoBindMatch the_matches match_msg
636 `thenDs` \ (binders, matching_code) ->
637 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
638 mkLams binders matching_code])
643 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
645 match_msg = case do_or_lc of
646 DoStmt -> "`do' statement"
647 ListComp -> "comprehension"
651 var_pat (WildPat _) = True
652 var_pat (VarPat _) = True