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, AutoScc(..) )
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(..), mkStrLit )
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 NoSccs 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)
188 = returnDs (mkLit (MachLitLit str ty))
190 = case (maybeBoxedPrimType ty) of
191 Just (boxing_data_con, prim_ty) ->
192 returnDs ( mkConApp boxing_data_con [mkLit (MachLitLit str prim_ty)] )
196 [ hcat [ text "Cannot see data constructor of ``literal-literal''s type: "
197 , text "value:", quotes (quotes (ptext str))
198 , text "; type: ", ppr ty
200 , text "Try compiling with -fno-prune-tydecls."
205 = case (maybeBoxedPrimType ty) of
206 Just (boxing_data_con, prim_ty) -> (boxing_data_con, prim_ty)
208 -> pprPanic "ERROR: ``literal-literal'' not a single-constructor type: "
209 (hcat [ptext str, text "; type: ", ppr ty])
211 dsExpr (HsLitOut (HsInt i) ty)
212 = returnDs (mkLit (NoRepInteger i ty))
214 dsExpr (HsLitOut (HsFrac r) ty)
215 = returnDs (mkLit (NoRepRational r ty))
217 -- others where we know what to do:
219 dsExpr (HsLitOut (HsIntPrim i) _)
220 | (i >= toInteger minInt && i <= toInteger maxInt)
221 = returnDs (mkLit (mkMachInt i))
223 = error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
225 dsExpr (HsLitOut (HsFloatPrim f) _)
226 = returnDs (mkLit (MachFloat f))
227 -- ToDo: range checking needed!
229 dsExpr (HsLitOut (HsDoublePrim d) _)
230 = returnDs (mkLit (MachDouble d))
231 -- ToDo: range checking needed!
233 dsExpr (HsLitOut (HsChar c) _)
234 = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
236 dsExpr (HsLitOut (HsCharPrim c) _)
237 = returnDs (mkLit (MachChar c))
239 dsExpr (HsLitOut (HsStringPrim s) _)
240 = returnDs (mkLit (MachStr s))
242 -- end of literals magic. --
244 dsExpr expr@(HsLam a_Match)
245 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
246 returnDs (mkLams binders matching_code)
248 dsExpr expr@(HsApp fun arg)
249 = dsExpr fun `thenDs` \ core_fun ->
250 dsExpr arg `thenDs` \ core_arg ->
251 returnDs (core_fun `App` core_arg)
255 Operator sections. At first it looks as if we can convert
264 But no! expr might be a redex, and we can lose laziness badly this
269 for example. So we convert instead to
271 let y = expr in \x -> op y x
273 If \tr{expr} is actually just a variable, say, then the simplifier
277 dsExpr (OpApp e1 op _ e2)
278 = dsExpr op `thenDs` \ core_op ->
279 -- for the type of y, we need the type of op's 2nd argument
281 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
283 dsExpr e1 `thenDs` \ x_core ->
284 dsExpr e2 `thenDs` \ y_core ->
285 returnDs (mkApps core_op [x_core, y_core])
287 dsExpr (SectionL expr op)
288 = dsExpr op `thenDs` \ core_op ->
289 -- for the type of y, we need the type of op's 2nd argument
291 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
293 dsExpr expr `thenDs` \ x_core ->
294 newSysLocalDs x_ty `thenDs` \ x_id ->
295 newSysLocalDs y_ty `thenDs` \ y_id ->
297 returnDs (bindNonRec x_id x_core $
298 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
300 -- dsExpr (SectionR op expr) -- \ x -> op x expr
301 dsExpr (SectionR op expr)
302 = dsExpr op `thenDs` \ core_op ->
303 -- for the type of x, we need the type of op's 2nd argument
305 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
307 dsExpr expr `thenDs` \ y_core ->
308 newSysLocalDs x_ty `thenDs` \ x_id ->
309 newSysLocalDs y_ty `thenDs` \ y_id ->
311 returnDs (bindNonRec y_id y_core $
312 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
314 dsExpr (CCall label args may_gc is_asm result_ty)
315 = mapDs dsExpr args `thenDs` \ core_args ->
316 dsCCall label core_args may_gc is_asm result_ty
317 -- dsCCall does all the unboxification, etc.
319 dsExpr (HsSCC cc expr)
320 = dsExpr expr `thenDs` \ core_expr ->
321 getModuleAndGroupDs `thenDs` \ (mod_name, group_name) ->
322 returnDs (Note (SCC (mkUserCC cc mod_name group_name)) core_expr)
324 -- special case to handle unboxed tuple patterns.
326 dsExpr (HsCase discrim matches@[Match _ [TuplePat ps boxed] _ _] src_loc)
327 | not boxed && all var_pat ps
328 = putSrcLocDs src_loc $
329 dsExpr discrim `thenDs` \ core_discrim ->
330 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
331 case matching_code of
332 Case (Var x) bndr alts | x == discrim_var ->
333 returnDs (Case core_discrim bndr alts)
334 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
336 dsExpr (HsCase discrim matches src_loc)
337 = putSrcLocDs src_loc $
338 dsExpr discrim `thenDs` \ core_discrim ->
339 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
340 returnDs (bindNonRec discrim_var core_discrim matching_code)
342 dsExpr (HsLet binds body)
343 = dsExpr body `thenDs` \ body' ->
346 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
347 | maybeToBool maybe_list_comp
348 = -- Special case for list comprehensions
349 putSrcLocDs src_loc $
350 dsListComp stmts elt_ty
353 = putSrcLocDs src_loc $
354 dsDo do_or_lc stmts return_id then_id fail_id result_ty
357 = case (do_or_lc, splitTyConApp_maybe result_ty) of
358 (ListComp, Just (tycon, [elt_ty]))
362 -- We need the ListComp form to use deListComp (rather than the "do" form)
363 -- because the "return" in a do block is a call to "PrelBase.return", and
364 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
366 Just elt_ty = maybe_list_comp
368 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
369 = putSrcLocDs src_loc $
370 dsExpr guard_expr `thenDs` \ core_guard ->
371 dsExpr then_expr `thenDs` \ core_then ->
372 dsExpr else_expr `thenDs` \ core_else ->
373 returnDs (mkIfThenElse core_guard core_then core_else)
377 Type lambda and application
378 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
380 dsExpr (TyLam tyvars expr)
381 = dsExpr expr `thenDs` \ core_expr ->
382 returnDs (mkLams tyvars core_expr)
384 dsExpr (TyApp expr tys)
385 = dsExpr expr `thenDs` \ core_expr ->
386 returnDs (mkTyApps core_expr tys)
390 Various data construction things
391 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
393 dsExpr (ExplicitListOut ty xs)
396 list_ty = mkListTy ty
398 go [] = returnDs (mkNilExpr ty)
399 go (x:xs) = dsExpr x `thenDs` \ core_x ->
400 go xs `thenDs` \ core_xs ->
401 returnDs (mkConApp consDataCon [Type ty, core_x, core_xs])
403 dsExpr (ExplicitTuple expr_list boxed)
404 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
405 returnDs (mkConApp ((if boxed
407 else unboxedTupleCon) (length expr_list))
408 (map (Type . coreExprType) core_exprs ++ core_exprs))
410 dsExpr (HsCon con_id [ty] [arg])
412 = dsExpr arg `thenDs` \ arg' ->
413 returnDs (Note (Coerce result_ty (coreExprType arg')) arg')
415 result_ty = mkTyConApp tycon [ty]
416 tycon = dataConTyCon con_id
418 dsExpr (HsCon con_id tys args)
419 = mapDs dsExpr args `thenDs` \ args2 ->
420 returnDs (mkConApp con_id (map Type tys ++ args2))
422 dsExpr (ArithSeqOut expr (From from))
423 = dsExpr expr `thenDs` \ expr2 ->
424 dsExpr from `thenDs` \ from2 ->
425 returnDs (App expr2 from2)
427 dsExpr (ArithSeqOut expr (FromTo from two))
428 = dsExpr expr `thenDs` \ expr2 ->
429 dsExpr from `thenDs` \ from2 ->
430 dsExpr two `thenDs` \ two2 ->
431 returnDs (mkApps expr2 [from2, two2])
433 dsExpr (ArithSeqOut expr (FromThen from thn))
434 = dsExpr expr `thenDs` \ expr2 ->
435 dsExpr from `thenDs` \ from2 ->
436 dsExpr thn `thenDs` \ thn2 ->
437 returnDs (mkApps expr2 [from2, thn2])
439 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
440 = dsExpr expr `thenDs` \ expr2 ->
441 dsExpr from `thenDs` \ from2 ->
442 dsExpr thn `thenDs` \ thn2 ->
443 dsExpr two `thenDs` \ two2 ->
444 returnDs (mkApps expr2 [from2, thn2, two2])
447 Record construction and update
448 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
449 For record construction we do this (assuming T has three arguments)
453 let err = /\a -> recConErr a
454 T (recConErr t1 "M.lhs/230/op1")
456 (recConErr t1 "M.lhs/230/op3")
458 recConErr then converts its arugment string into a proper message
459 before printing it as
461 M.lhs, line 230: missing field op1 was evaluated
465 dsExpr (RecordConOut data_con con_expr rbinds)
466 = dsExpr con_expr `thenDs` \ con_expr' ->
468 (arg_tys, _) = splitFunTys (coreExprType con_expr')
471 = case [rhs | (sel_id,rhs,_) <- rbinds,
472 lbl == recordSelectorFieldLabel sel_id] of
473 (rhs:rhss) -> ASSERT( null rhss )
475 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
477 mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys (dataConFieldLabels data_con)) `thenDs` \ con_args ->
478 returnDs (mkApps con_expr' con_args)
481 Record update is a little harder. Suppose we have the decl:
483 data T = T1 {op1, op2, op3 :: Int}
484 | T2 {op4, op2 :: Int}
487 Then we translate as follows:
493 T1 op1 _ op3 -> T1 op1 op2 op3
494 T2 op4 _ -> T2 op4 op2
495 other -> recUpdError "M.lhs/230"
497 It's important that we use the constructor Ids for T1, T2 etc on the
498 RHSs, and do not generate a Core Con directly, because the constructor
499 might do some argument-evaluation first; and may have to throw away some
503 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
504 = dsExpr record_expr `thenDs` \ record_expr' ->
506 -- Desugar the rbinds, and generate let-bindings if
507 -- necessary so that we don't lose sharing
510 ds_rbind (sel_id, rhs, pun_flag)
511 = dsExpr rhs `thenDs` \ rhs' ->
512 returnDs (recordSelectorFieldLabel sel_id, rhs')
514 mapDs ds_rbind rbinds `thenDs` \ rbinds' ->
516 record_in_ty = coreExprType record_expr'
517 (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
518 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
519 cons_to_upd = filter has_all_fields cons
521 -- initial_args are passed to every constructor
522 initial_args = map Type out_inst_tys ++ map Var dicts
524 mk_val_arg field old_arg_id
525 = case [rhs | (f, rhs) <- rbinds', field == f] of
526 (rhs:rest) -> ASSERT(null rest) rhs
530 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
532 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
533 (dataConFieldLabels con) arg_ids
534 rhs = mkApps (mkApps (Var (dataConId con)) initial_args) val_args
536 returnDs (DataCon con, arg_ids, rhs)
539 | length cons_to_upd == length cons
542 = mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty "" `thenDs` \ err ->
543 returnDs [(DEFAULT, [], err)]
545 -- Record stuff doesn't work for existentials
546 ASSERT( all (not . isExistentialDataCon) cons )
548 newSysLocalDs record_in_ty `thenDs` \ case_bndr ->
549 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
550 mk_default `thenDs` \ deflt ->
552 returnDs (Case record_expr' case_bndr (alts ++ deflt))
554 has_all_fields :: DataCon -> Bool
555 has_all_fields con_id
558 con_fields = dataConFieldLabels con_id
559 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
562 Dictionary lambda and application
563 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
564 @DictLam@ and @DictApp@ turn into the regular old things.
565 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
566 complicated; reminiscent of fully-applied constructors.
568 dsExpr (DictLam dictvars expr)
569 = dsExpr expr `thenDs` \ core_expr ->
570 returnDs (mkLams dictvars core_expr)
574 dsExpr (DictApp expr dicts) -- becomes a curried application
575 = dsExpr expr `thenDs` \ core_expr ->
576 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
582 -- HsSyn constructs that just shouldn't be here:
583 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
584 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
585 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
586 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
589 out_of_range_msg -- ditto
590 = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
593 %--------------------------------------------------------------------
595 Basically does the translation given in the Haskell~1.3 report:
600 -> Id -- id for: return m
601 -> Id -- id for: (>>=) m
602 -> Id -- id for: fail m
603 -> Type -- Element type; the whole expression has type (m t)
606 dsDo do_or_lc stmts return_id then_id fail_id result_ty
608 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
611 = dsExpr expr `thenDs` \ expr2 ->
612 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
614 go (GuardStmt expr locn : stmts)
615 = do_expr expr locn `thenDs` \ expr2 ->
616 go stmts `thenDs` \ rest ->
617 let msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn) in
618 returnDs (mkIfThenElse expr2
620 (App (App (Var fail_id)
622 (mkLit (mkStrLit msg stringTy))))
624 go (ExprStmt expr locn : stmts)
625 = do_expr expr locn `thenDs` \ expr2 ->
627 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
632 go stmts `thenDs` \ rest ->
633 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
634 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
635 Lam ignored_result_id rest])
637 go (LetStmt binds : stmts )
638 = go stmts `thenDs` \ rest ->
641 go (BindStmt pat expr locn : stmts)
643 dsExpr expr `thenDs` \ expr2 ->
645 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
646 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty]) (HsLitOut (HsString (_PK_ msg)) stringTy)
647 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
648 main_match = mkSimpleMatch [pat]
649 (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty locn)
650 (Just result_ty) locn
652 | failureFreePat pat = [main_match]
655 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
658 matchWrapper DoBindMatch the_matches match_msg
659 `thenDs` \ (binders, matching_code) ->
660 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
661 mkLams binders matching_code])
666 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
668 match_msg = case do_or_lc of
669 DoStmt -> "`do' statement"
670 ListComp -> "comprehension"
674 var_pat (WildPat _) = True
675 var_pat (VarPat _) = True