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, mkDsLets, mkConsExpr, mkNilExpr )
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 PrelInfo ( 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, isNotUsgTy, unUsgTy,
44 splitAppTy, isUnLiftedType, Type
46 import TysWiredIn ( tupleCon, unboxedTupleCon,
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 -- Silently ignore INLINE pragmas...
86 dsLet (MonoBind (AbsBinds [] [] binder_triples inlines
87 (PatMonoBind pat grhss loc)) sigs is_rec) body
88 | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
89 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
91 dsGuarded grhss `thenDs` \ rhs ->
93 body' = foldr bind body binder_triples
94 bind (tyvars, g, l) body = ASSERT( null tyvars )
95 bindNonRec g (Var l) body
97 mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat))
98 `thenDs` \ error_expr ->
99 matchSimply rhs PatBindMatch pat body' error_expr
101 result_ty = coreExprType body
103 -- Ordinary case for bindings
104 dsLet (MonoBind binds sigs is_rec) body
105 = dsMonoBinds NoSccs binds [] `thenDs` \ prs ->
107 Recursive -> returnDs (Let (Rec prs) body)
108 NonRecursive -> returnDs (mkDsLets [NonRec b r | (b,r) <- prs] body)
111 %************************************************************************
113 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
115 %************************************************************************
118 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
120 dsExpr e@(HsVar var) = returnDs (Var var)
121 dsExpr e@(HsIPVar var) = returnDs (Var var)
124 %************************************************************************
126 \subsection[DsExpr-literals]{Literals}
128 %************************************************************************
130 We give int/float literals type @Integer@ and @Rational@, respectively.
131 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
134 ToDo: put in range checks for when converting ``@i@''
135 (or should that be in the typechecker?)
137 For numeric literals, we try to detect there use at a standard type
138 (@Int@, @Float@, etc.) are directly put in the right constructor.
139 [NB: down with the @App@ conversion.]
140 Otherwise, we punt, putting in a @NoRep@ Core literal (where the
141 representation decisions are delayed)...
143 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
146 dsExpr (HsLitOut (HsString s) _)
148 = returnDs (mkNilExpr charTy)
152 the_char = mkConApp charDataCon [mkLit (MachChar (_HEAD_ s))]
153 the_nil = mkNilExpr charTy
154 the_cons = mkConsExpr charTy the_char the_nil
159 -- "_" => build (\ c n -> c 'c' n) -- LATER
161 -- otherwise, leave it as a NoRepStr;
162 -- the Core-to-STG pass will wrap it in an application of "unpackCStringId".
164 dsExpr (HsLitOut (HsString str) _)
165 = returnDs (mkStringLitFS str)
167 dsExpr (HsLitOut (HsLitLit str) ty)
169 = returnDs (mkLit (MachLitLit str ty))
171 = case (maybeBoxedPrimType ty) of
172 Just (boxing_data_con, prim_ty) ->
173 returnDs ( mkConApp boxing_data_con [mkLit (MachLitLit str prim_ty)] )
177 [ hcat [ text "Cannot see data constructor of ``literal-literal''s type: "
178 , text "value:", quotes (quotes (ptext str))
179 , text "; type: ", ppr ty
181 , text "Try compiling with -fno-prune-tydecls."
186 = case (maybeBoxedPrimType ty) of
187 Just (boxing_data_con, prim_ty) -> (boxing_data_con, prim_ty)
189 -> pprPanic "ERROR: ``literal-literal'' not a single-constructor type: "
190 (hcat [ptext str, text "; type: ", ppr ty])
192 dsExpr (HsLitOut (HsInt i) ty)
193 = returnDs (mkLit (NoRepInteger i ty))
195 dsExpr (HsLitOut (HsFrac r) ty)
196 = returnDs (mkLit (NoRepRational r ty))
198 -- others where we know what to do:
200 dsExpr (HsLitOut (HsIntPrim i) _)
201 | (i >= toInteger minInt && i <= toInteger maxInt)
202 = returnDs (mkLit (mkMachInt i))
204 = error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
206 dsExpr (HsLitOut (HsFloatPrim f) _)
207 = returnDs (mkLit (MachFloat f))
208 -- ToDo: range checking needed!
210 dsExpr (HsLitOut (HsDoublePrim d) _)
211 = returnDs (mkLit (MachDouble d))
212 -- ToDo: range checking needed!
214 dsExpr (HsLitOut (HsChar c) _)
215 = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
217 dsExpr (HsLitOut (HsCharPrim c) _)
218 = returnDs (mkLit (MachChar c))
220 dsExpr (HsLitOut (HsStringPrim s) _)
221 = returnDs (mkLit (MachStr s))
223 -- end of literals magic. --
225 dsExpr expr@(HsLam a_Match)
226 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
227 returnDs (mkLams binders matching_code)
229 dsExpr expr@(HsApp fun arg)
230 = dsExpr fun `thenDs` \ core_fun ->
231 dsExpr arg `thenDs` \ core_arg ->
232 returnDs (core_fun `App` core_arg)
236 Operator sections. At first it looks as if we can convert
245 But no! expr might be a redex, and we can lose laziness badly this
250 for example. So we convert instead to
252 let y = expr in \x -> op y x
254 If \tr{expr} is actually just a variable, say, then the simplifier
258 dsExpr (OpApp e1 op _ e2)
259 = dsExpr op `thenDs` \ core_op ->
260 -- for the type of y, we need the type of op's 2nd argument
261 dsExpr e1 `thenDs` \ x_core ->
262 dsExpr e2 `thenDs` \ y_core ->
263 returnDs (mkApps core_op [x_core, y_core])
265 dsExpr (SectionL expr op)
266 = dsExpr op `thenDs` \ core_op ->
267 -- for the type of y, we need the type of op's 2nd argument
269 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
271 dsExpr expr `thenDs` \ x_core ->
272 newSysLocalDs x_ty `thenDs` \ x_id ->
273 newSysLocalDs y_ty `thenDs` \ y_id ->
275 returnDs (bindNonRec x_id x_core $
276 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
278 -- dsExpr (SectionR op expr) -- \ x -> op x expr
279 dsExpr (SectionR op expr)
280 = dsExpr op `thenDs` \ core_op ->
281 -- for the type of x, we need the type of op's 2nd argument
283 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
285 dsExpr expr `thenDs` \ y_core ->
286 newSysLocalDs x_ty `thenDs` \ x_id ->
287 newSysLocalDs y_ty `thenDs` \ y_id ->
289 returnDs (bindNonRec y_id y_core $
290 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
292 dsExpr (CCall lbl args may_gc is_asm result_ty)
293 = mapDs dsExpr args `thenDs` \ core_args ->
294 dsCCall lbl core_args may_gc is_asm result_ty
295 -- dsCCall does all the unboxification, etc.
297 dsExpr (HsSCC cc expr)
298 = dsExpr expr `thenDs` \ core_expr ->
299 getModuleAndGroupDs `thenDs` \ (mod_name, group_name) ->
300 returnDs (Note (SCC (mkUserCC cc mod_name group_name)) core_expr)
302 -- special case to handle unboxed tuple patterns.
304 dsExpr (HsCase discrim matches@[Match _ [TuplePat ps boxed] _ _] src_loc)
305 | not boxed && all var_pat ps
306 = putSrcLocDs src_loc $
307 dsExpr discrim `thenDs` \ core_discrim ->
308 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
309 case matching_code of
310 Case (Var x) bndr alts | x == discrim_var ->
311 returnDs (Case core_discrim bndr alts)
312 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
314 dsExpr (HsCase discrim matches src_loc)
315 = putSrcLocDs src_loc $
316 dsExpr discrim `thenDs` \ core_discrim ->
317 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
318 returnDs (bindNonRec discrim_var core_discrim matching_code)
320 dsExpr (HsLet binds body)
321 = dsExpr body `thenDs` \ body' ->
324 dsExpr (HsWith expr binds)
325 = dsExpr expr `thenDs` \ expr' ->
326 foldlDs dsIPBind expr' binds
329 = dsExpr e `thenDs` \ e' ->
330 returnDs (Let (NonRec n e') body)
332 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
333 | maybeToBool maybe_list_comp
334 = -- Special case for list comprehensions
335 putSrcLocDs src_loc $
336 dsListComp stmts elt_ty
339 = putSrcLocDs src_loc $
340 dsDo do_or_lc stmts return_id then_id fail_id result_ty
343 = case (do_or_lc, splitTyConApp_maybe result_ty) of
344 (ListComp, Just (tycon, [elt_ty]))
348 -- We need the ListComp form to use deListComp (rather than the "do" form)
349 -- because the "return" in a do block is a call to "PrelBase.return", and
350 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
352 Just elt_ty = maybe_list_comp
354 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
355 = putSrcLocDs src_loc $
356 dsExpr guard_expr `thenDs` \ core_guard ->
357 dsExpr then_expr `thenDs` \ core_then ->
358 dsExpr else_expr `thenDs` \ core_else ->
359 returnDs (mkIfThenElse core_guard core_then core_else)
364 \underline{\bf Type lambda and application}
365 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
367 dsExpr (TyLam tyvars expr)
368 = dsExpr expr `thenDs` \ core_expr ->
369 returnDs (mkLams tyvars core_expr)
371 dsExpr (TyApp expr tys)
372 = dsExpr expr `thenDs` \ core_expr ->
373 returnDs (mkTyApps core_expr tys)
378 \underline{\bf Various data construction things}
379 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
381 dsExpr (ExplicitListOut ty xs)
384 list_ty = mkListTy ty
386 go [] = returnDs (mkNilExpr ty)
387 go (x:xs) = dsExpr x `thenDs` \ core_x ->
388 go xs `thenDs` \ core_xs ->
389 ASSERT( isNotUsgTy ty )
390 returnDs (mkConsExpr ty core_x core_xs)
392 dsExpr (ExplicitTuple expr_list boxed)
393 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
394 returnDs (mkConApp ((if boxed
396 else unboxedTupleCon) (length expr_list))
397 (map (Type . unUsgTy . coreExprType) core_exprs ++ core_exprs))
398 -- the above unUsgTy is *required* -- KSW 1999-04-07
400 dsExpr (HsCon con_id [ty] [arg])
402 = dsExpr arg `thenDs` \ arg' ->
403 returnDs (Note (Coerce result_ty (unUsgTy (coreExprType arg'))) arg')
405 result_ty = mkTyConApp tycon [ty]
406 tycon = dataConTyCon con_id
408 dsExpr (HsCon con_id tys args)
409 = mapDs dsExpr args `thenDs` \ args2 ->
410 ASSERT( all isNotUsgTy tys )
411 returnDs (mkConApp con_id (map Type tys ++ args2))
413 dsExpr (ArithSeqOut expr (From from))
414 = dsExpr expr `thenDs` \ expr2 ->
415 dsExpr from `thenDs` \ from2 ->
416 returnDs (App expr2 from2)
418 dsExpr (ArithSeqOut expr (FromTo from two))
419 = dsExpr expr `thenDs` \ expr2 ->
420 dsExpr from `thenDs` \ from2 ->
421 dsExpr two `thenDs` \ two2 ->
422 returnDs (mkApps expr2 [from2, two2])
424 dsExpr (ArithSeqOut expr (FromThen from thn))
425 = dsExpr expr `thenDs` \ expr2 ->
426 dsExpr from `thenDs` \ from2 ->
427 dsExpr thn `thenDs` \ thn2 ->
428 returnDs (mkApps expr2 [from2, thn2])
430 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
431 = dsExpr expr `thenDs` \ expr2 ->
432 dsExpr from `thenDs` \ from2 ->
433 dsExpr thn `thenDs` \ thn2 ->
434 dsExpr two `thenDs` \ two2 ->
435 returnDs (mkApps expr2 [from2, thn2, two2])
439 \underline{\bf Record construction and update}
440 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
441 For record construction we do this (assuming T has three arguments)
445 let err = /\a -> recConErr a
446 T (recConErr t1 "M.lhs/230/op1")
448 (recConErr t1 "M.lhs/230/op3")
450 @recConErr@ then converts its arugment string into a proper message
451 before printing it as
453 M.lhs, line 230: missing field op1 was evaluated
456 We also handle @C{}@ as valid construction syntax for an unlabelled
457 constructor @C@, setting all of @C@'s fields to bottom.
460 dsExpr (RecordConOut data_con con_expr rbinds)
461 = dsExpr con_expr `thenDs` \ con_expr' ->
463 (arg_tys, _) = splitFunTys (coreExprType con_expr')
466 = case [rhs | (sel_id,rhs,_) <- rbinds,
467 lbl == recordSelectorFieldLabel sel_id] of
468 (rhs:rhss) -> ASSERT( null rhss )
470 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
471 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
473 labels = dataConFieldLabels data_con
477 then mapDs unlabelled_bottom arg_tys
478 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
479 `thenDs` \ con_args ->
481 returnDs (mkApps con_expr' con_args)
484 Record update is a little harder. Suppose we have the decl:
486 data T = T1 {op1, op2, op3 :: Int}
487 | T2 {op4, op2 :: Int}
490 Then we translate as follows:
496 T1 op1 _ op3 -> T1 op1 op2 op3
497 T2 op4 _ -> T2 op4 op2
498 other -> recUpdError "M.lhs/230"
500 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
501 RHSs, and do not generate a Core @Con@ directly, because the constructor
502 might do some argument-evaluation first; and may have to throw away some
506 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
507 = dsExpr record_expr `thenDs` \ record_expr' ->
509 -- Desugar the rbinds, and generate let-bindings if
510 -- necessary so that we don't lose sharing
513 ds_rbind (sel_id, rhs, pun_flag)
514 = dsExpr rhs `thenDs` \ rhs' ->
515 returnDs (recordSelectorFieldLabel sel_id, rhs')
517 mapDs ds_rbind rbinds `thenDs` \ rbinds' ->
519 record_in_ty = coreExprType record_expr'
520 (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
521 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
522 cons_to_upd = filter has_all_fields cons
524 -- initial_args are passed to every constructor
525 initial_args = map Type out_inst_tys ++ map Var dicts
527 mk_val_arg field old_arg_id
528 = case [rhs | (f, rhs) <- rbinds', field == f] of
529 (rhs:rest) -> ASSERT(null rest) rhs
533 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
534 -- This call to dataConArgTys won't work for existentials
536 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
537 (dataConFieldLabels con) arg_ids
538 rhs = mkApps (mkApps (Var (dataConId con)) initial_args) val_args
540 returnDs (DataCon con, arg_ids, rhs)
543 | length cons_to_upd == length cons
546 = mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty "" `thenDs` \ err ->
547 returnDs [(DEFAULT, [], err)]
549 -- Record stuff doesn't work for existentials
550 ASSERT( all (not . isExistentialDataCon) cons )
552 newSysLocalDs record_in_ty `thenDs` \ case_bndr ->
553 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
554 mk_default `thenDs` \ deflt ->
556 returnDs (Case record_expr' case_bndr (alts ++ deflt))
558 has_all_fields :: DataCon -> Bool
559 has_all_fields con_id
562 con_fields = dataConFieldLabels con_id
563 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
568 \underline{\bf Dictionary lambda and application}
569 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
570 @DictLam@ and @DictApp@ turn into the regular old things.
571 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
572 complicated; reminiscent of fully-applied constructors.
574 dsExpr (DictLam dictvars expr)
575 = dsExpr expr `thenDs` \ core_expr ->
576 returnDs (mkLams dictvars core_expr)
580 dsExpr (DictApp expr dicts) -- becomes a curried application
581 = dsExpr expr `thenDs` \ core_expr ->
582 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
588 -- HsSyn constructs that just shouldn't be here:
589 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
590 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
591 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
592 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
595 out_of_range_msg -- ditto
596 = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
599 %--------------------------------------------------------------------
601 Basically does the translation given in the Haskell~1.3 report:
606 -> Id -- id for: return m
607 -> Id -- id for: (>>=) m
608 -> Id -- id for: fail m
609 -> Type -- Element type; the whole expression has type (m t)
612 dsDo do_or_lc stmts return_id then_id fail_id result_ty
614 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
617 = dsExpr expr `thenDs` \ expr2 ->
618 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
620 go (GuardStmt expr locn : stmts)
621 = do_expr expr locn `thenDs` \ expr2 ->
622 go stmts `thenDs` \ rest ->
623 let msg = ASSERT( isNotUsgTy b_ty )
624 "Pattern match failure in do expression, " ++ showSDoc (ppr locn) in
625 returnDs (mkIfThenElse expr2
627 (App (App (Var fail_id)
629 (mkLit (mkStrLit msg stringTy))))
631 go (ExprStmt expr locn : stmts)
632 = do_expr expr locn `thenDs` \ expr2 ->
634 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
639 go stmts `thenDs` \ rest ->
640 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
641 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
642 Lam ignored_result_id rest])
644 go (LetStmt binds : stmts )
645 = go stmts `thenDs` \ rest ->
648 go (BindStmt pat expr locn : stmts)
650 dsExpr expr `thenDs` \ expr2 ->
652 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
653 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
654 (HsLitOut (HsString (_PK_ msg)) stringTy)
655 msg = ASSERT2( isNotUsgTy a_ty, ppr a_ty )
656 ASSERT2( isNotUsgTy b_ty, ppr b_ty )
657 "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
658 main_match = mkSimpleMatch [pat]
659 (HsDoOut do_or_lc stmts return_id then_id
660 fail_id result_ty locn)
661 (Just result_ty) locn
663 | failureFreePat pat = [main_match]
666 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
669 matchWrapper DoBindMatch the_matches match_msg
670 `thenDs` \ (binders, matching_code) ->
671 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
672 mkLams binders matching_code])
677 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
679 match_msg = case do_or_lc of
680 DoStmt -> "`do' statement"
681 ListComp -> "comprehension"
685 var_pat (WildPat _) = True
686 var_pat (VarPat _) = True