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 (PatMonoBind pat grhss loc)) sigs is_rec) body
87 | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
88 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
90 dsGuarded grhss `thenDs` \ rhs ->
92 body' = foldr bind body binder_triples
93 bind (tyvars, g, l) body = ASSERT( null tyvars )
94 bindNonRec g (Var l) body
96 mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat)) `thenDs` \ error_expr ->
97 matchSimply rhs PatBindMatch pat body' error_expr
99 result_ty = coreExprType body
101 -- Ordinary case for bindings
102 dsLet (MonoBind binds sigs is_rec) body
103 = dsMonoBinds NoSccs binds [] `thenDs` \ prs ->
105 Recursive -> returnDs (Let (Rec prs) body)
106 NonRecursive -> returnDs (mkDsLets [NonRec b r | (b,r) <- prs] body)
109 %************************************************************************
111 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
113 %************************************************************************
116 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
118 dsExpr e@(HsVar var) = returnDs (Var var)
121 %************************************************************************
123 \subsection[DsExpr-literals]{Literals}
125 %************************************************************************
127 We give int/float literals type Integer and Rational, respectively.
128 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
131 ToDo: put in range checks for when converting "i"
132 (or should that be in the typechecker?)
134 For numeric literals, we try to detect there use at a standard type
135 (Int, Float, etc.) are directly put in the right constructor.
136 [NB: down with the @App@ conversion.]
137 Otherwise, we punt, putting in a "NoRep" Core literal (where the
138 representation decisions are delayed)...
140 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
143 dsExpr (HsLitOut (HsString s) _)
145 = returnDs (mkNilExpr charTy)
149 the_char = mkConApp charDataCon [mkLit (MachChar (_HEAD_ s))]
150 the_nil = mkNilExpr charTy
151 the_cons = mkConsExpr charTy the_char the_nil
156 -- "_" => build (\ c n -> c 'c' n) -- LATER
158 -- "str" ==> build (\ c n -> foldr charTy T c n "str")
161 dsExpr (HsLitOut (HsString str) _)
162 = newTyVarsDs [alphaTyVar] `thenDs` \ [new_tyvar] ->
164 new_ty = mkTyVarTy new_tyvar
167 charTy `mkFunTy` (new_ty `mkFunTy` new_ty),
169 mkForallTy [alphaTyVar]
170 ((charTy `mkFunTy` (alphaTy `mkFunTy` alphaTy))
171 `mkFunTy` (alphaTy `mkFunTy` alphaTy))
172 ] `thenDs` \ [c,n,g] ->
173 returnDs (mkBuild charTy new_tyvar c n g (
175 (CoTyApp (CoTyApp (Var foldrId) charTy) new_ty) *** ensure non-prim type ***
176 [VarArg c,VarArg n,LitArg (NoRepStr str)]))
179 -- otherwise, leave it as a NoRepStr;
180 -- the Core-to-STG pass will wrap it in an application of "unpackCStringId".
182 dsExpr (HsLitOut (HsString str) _)
183 = returnDs (mkLit (NoRepStr str stringTy))
185 dsExpr (HsLitOut (HsLitLit str) ty)
187 = returnDs (mkLit (MachLitLit str ty))
189 = case (maybeBoxedPrimType ty) of
190 Just (boxing_data_con, prim_ty) ->
191 returnDs ( mkConApp boxing_data_con [mkLit (MachLitLit str prim_ty)] )
195 [ hcat [ text "Cannot see data constructor of ``literal-literal''s type: "
196 , text "value:", quotes (quotes (ptext str))
197 , text "; type: ", ppr ty
199 , text "Try compiling with -fno-prune-tydecls."
204 = case (maybeBoxedPrimType ty) of
205 Just (boxing_data_con, prim_ty) -> (boxing_data_con, prim_ty)
207 -> pprPanic "ERROR: ``literal-literal'' not a single-constructor type: "
208 (hcat [ptext str, text "; type: ", ppr ty])
210 dsExpr (HsLitOut (HsInt i) ty)
211 = returnDs (mkLit (NoRepInteger i ty))
213 dsExpr (HsLitOut (HsFrac r) ty)
214 = returnDs (mkLit (NoRepRational r ty))
216 -- others where we know what to do:
218 dsExpr (HsLitOut (HsIntPrim i) _)
219 | (i >= toInteger minInt && i <= toInteger maxInt)
220 = returnDs (mkLit (mkMachInt i))
222 = error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
224 dsExpr (HsLitOut (HsFloatPrim f) _)
225 = returnDs (mkLit (MachFloat f))
226 -- ToDo: range checking needed!
228 dsExpr (HsLitOut (HsDoublePrim d) _)
229 = returnDs (mkLit (MachDouble d))
230 -- ToDo: range checking needed!
232 dsExpr (HsLitOut (HsChar c) _)
233 = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
235 dsExpr (HsLitOut (HsCharPrim c) _)
236 = returnDs (mkLit (MachChar c))
238 dsExpr (HsLitOut (HsStringPrim s) _)
239 = returnDs (mkLit (MachStr s))
241 -- end of literals magic. --
243 dsExpr expr@(HsLam a_Match)
244 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
245 returnDs (mkLams binders matching_code)
247 dsExpr expr@(HsApp fun arg)
248 = dsExpr fun `thenDs` \ core_fun ->
249 dsExpr arg `thenDs` \ core_arg ->
250 returnDs (core_fun `App` core_arg)
254 Operator sections. At first it looks as if we can convert
263 But no! expr might be a redex, and we can lose laziness badly this
268 for example. So we convert instead to
270 let y = expr in \x -> op y x
272 If \tr{expr} is actually just a variable, say, then the simplifier
276 dsExpr (OpApp e1 op _ e2)
277 = dsExpr op `thenDs` \ core_op ->
278 -- for the type of y, we need the type of op's 2nd argument
279 dsExpr e1 `thenDs` \ x_core ->
280 dsExpr e2 `thenDs` \ y_core ->
281 returnDs (mkApps core_op [x_core, y_core])
283 dsExpr (SectionL expr op)
284 = dsExpr op `thenDs` \ core_op ->
285 -- for the type of y, we need the type of op's 2nd argument
287 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
289 dsExpr expr `thenDs` \ x_core ->
290 newSysLocalDs x_ty `thenDs` \ x_id ->
291 newSysLocalDs y_ty `thenDs` \ y_id ->
293 returnDs (bindNonRec x_id x_core $
294 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
296 -- dsExpr (SectionR op expr) -- \ x -> op x expr
297 dsExpr (SectionR op expr)
298 = dsExpr op `thenDs` \ core_op ->
299 -- for the type of x, we need the type of op's 2nd argument
301 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
303 dsExpr expr `thenDs` \ y_core ->
304 newSysLocalDs x_ty `thenDs` \ x_id ->
305 newSysLocalDs y_ty `thenDs` \ y_id ->
307 returnDs (bindNonRec y_id y_core $
308 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
310 dsExpr (CCall label args may_gc is_asm result_ty)
311 = mapDs dsExpr args `thenDs` \ core_args ->
312 dsCCall label core_args may_gc is_asm result_ty
313 -- dsCCall does all the unboxification, etc.
315 dsExpr (HsSCC cc expr)
316 = dsExpr expr `thenDs` \ core_expr ->
317 getModuleAndGroupDs `thenDs` \ (mod_name, group_name) ->
318 returnDs (Note (SCC (mkUserCC cc mod_name group_name)) core_expr)
320 -- special case to handle unboxed tuple patterns.
322 dsExpr (HsCase discrim matches@[Match _ [TuplePat ps boxed] _ _] src_loc)
323 | not boxed && all var_pat ps
324 = putSrcLocDs src_loc $
325 dsExpr discrim `thenDs` \ core_discrim ->
326 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
327 case matching_code of
328 Case (Var x) bndr alts | x == discrim_var ->
329 returnDs (Case core_discrim bndr alts)
330 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
332 dsExpr (HsCase discrim matches src_loc)
333 = putSrcLocDs src_loc $
334 dsExpr discrim `thenDs` \ core_discrim ->
335 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
336 returnDs (bindNonRec discrim_var core_discrim matching_code)
338 dsExpr (HsLet binds body)
339 = dsExpr body `thenDs` \ body' ->
342 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
343 | maybeToBool maybe_list_comp
344 = -- Special case for list comprehensions
345 putSrcLocDs src_loc $
346 dsListComp stmts elt_ty
349 = putSrcLocDs src_loc $
350 dsDo do_or_lc stmts return_id then_id fail_id result_ty
353 = case (do_or_lc, splitTyConApp_maybe result_ty) of
354 (ListComp, Just (tycon, [elt_ty]))
358 -- We need the ListComp form to use deListComp (rather than the "do" form)
359 -- because the "return" in a do block is a call to "PrelBase.return", and
360 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
362 Just elt_ty = maybe_list_comp
364 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
365 = putSrcLocDs src_loc $
366 dsExpr guard_expr `thenDs` \ core_guard ->
367 dsExpr then_expr `thenDs` \ core_then ->
368 dsExpr else_expr `thenDs` \ core_else ->
369 returnDs (mkIfThenElse core_guard core_then core_else)
373 Type lambda and application
374 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
376 dsExpr (TyLam tyvars expr)
377 = dsExpr expr `thenDs` \ core_expr ->
378 returnDs (mkLams tyvars core_expr)
380 dsExpr (TyApp expr tys)
381 = dsExpr expr `thenDs` \ core_expr ->
382 returnDs (mkTyApps core_expr tys)
386 Various data construction things
387 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
389 dsExpr (ExplicitListOut ty xs)
392 list_ty = mkListTy ty
394 go [] = returnDs (mkNilExpr ty)
395 go (x:xs) = dsExpr x `thenDs` \ core_x ->
396 go xs `thenDs` \ core_xs ->
397 ASSERT( isNotUsgTy ty )
398 returnDs (mkConsExpr ty core_x core_xs)
400 dsExpr (ExplicitTuple expr_list boxed)
401 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
402 returnDs (mkConApp ((if boxed
404 else unboxedTupleCon) (length expr_list))
405 (map (Type . unUsgTy . coreExprType) core_exprs ++ core_exprs))
406 -- the above unUsgTy is *required* -- KSW 1999-04-07
408 dsExpr (HsCon con_id [ty] [arg])
410 = dsExpr arg `thenDs` \ arg' ->
411 returnDs (Note (Coerce result_ty (unUsgTy (coreExprType arg'))) arg')
413 result_ty = mkTyConApp tycon [ty]
414 tycon = dataConTyCon con_id
416 dsExpr (HsCon con_id tys args)
417 = mapDs dsExpr args `thenDs` \ args2 ->
418 ASSERT( all isNotUsgTy tys )
419 returnDs (mkConApp con_id (map Type tys ++ args2))
421 dsExpr (ArithSeqOut expr (From from))
422 = dsExpr expr `thenDs` \ expr2 ->
423 dsExpr from `thenDs` \ from2 ->
424 returnDs (App expr2 from2)
426 dsExpr (ArithSeqOut expr (FromTo from two))
427 = dsExpr expr `thenDs` \ expr2 ->
428 dsExpr from `thenDs` \ from2 ->
429 dsExpr two `thenDs` \ two2 ->
430 returnDs (mkApps expr2 [from2, two2])
432 dsExpr (ArithSeqOut expr (FromThen from thn))
433 = dsExpr expr `thenDs` \ expr2 ->
434 dsExpr from `thenDs` \ from2 ->
435 dsExpr thn `thenDs` \ thn2 ->
436 returnDs (mkApps expr2 [from2, thn2])
438 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
439 = dsExpr expr `thenDs` \ expr2 ->
440 dsExpr from `thenDs` \ from2 ->
441 dsExpr thn `thenDs` \ thn2 ->
442 dsExpr two `thenDs` \ two2 ->
443 returnDs (mkApps expr2 [from2, thn2, two2])
446 Record construction and update
447 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
448 For record construction we do this (assuming T has three arguments)
452 let err = /\a -> recConErr a
453 T (recConErr t1 "M.lhs/230/op1")
455 (recConErr t1 "M.lhs/230/op3")
457 recConErr then converts its arugment string into a proper message
458 before printing it as
460 M.lhs, line 230: Missing field in record construction op1
463 We also handle C{} as valid construction syntax for an unlabelled
464 constructor C, setting all of C's fields to bottom.
467 dsExpr (RecordConOut data_con con_expr rbinds)
468 = dsExpr con_expr `thenDs` \ con_expr' ->
470 (arg_tys, _) = splitFunTys (coreExprType con_expr')
473 = case [rhs | (sel_id,rhs,_) <- rbinds,
474 lbl == recordSelectorFieldLabel sel_id] of
475 (rhs:rhss) -> ASSERT( null rhss )
477 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
478 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
480 labels = dataConFieldLabels data_con
484 then mapDs unlabelled_bottom arg_tys
485 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
486 `thenDs` \ con_args ->
488 returnDs (mkApps con_expr' con_args)
491 Record update is a little harder. Suppose we have the decl:
493 data T = T1 {op1, op2, op3 :: Int}
494 | T2 {op4, op2 :: Int}
497 Then we translate as follows:
503 T1 op1 _ op3 -> T1 op1 op2 op3
504 T2 op4 _ -> T2 op4 op2
505 other -> recUpdError "M.lhs/230"
507 It's important that we use the constructor Ids for T1, T2 etc on the
508 RHSs, and do not generate a Core Con directly, because the constructor
509 might do some argument-evaluation first; and may have to throw away some
513 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
514 = dsExpr record_expr `thenDs` \ record_expr' ->
516 -- Desugar the rbinds, and generate let-bindings if
517 -- necessary so that we don't lose sharing
520 ds_rbind (sel_id, rhs, pun_flag)
521 = dsExpr rhs `thenDs` \ rhs' ->
522 returnDs (recordSelectorFieldLabel sel_id, rhs')
524 mapDs ds_rbind rbinds `thenDs` \ rbinds' ->
526 record_in_ty = coreExprType record_expr'
527 (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
528 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
529 cons_to_upd = filter has_all_fields cons
531 -- initial_args are passed to every constructor
532 initial_args = map Type out_inst_tys ++ map Var dicts
534 mk_val_arg field old_arg_id
535 = case [rhs | (f, rhs) <- rbinds', field == f] of
536 (rhs:rest) -> ASSERT(null rest) rhs
540 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
542 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
543 (dataConFieldLabels con) arg_ids
544 rhs = mkApps (mkApps (Var (dataConId con)) initial_args) val_args
546 returnDs (DataCon con, arg_ids, rhs)
549 | length cons_to_upd == length cons
552 = mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty "" `thenDs` \ err ->
553 returnDs [(DEFAULT, [], err)]
555 -- Record stuff doesn't work for existentials
556 ASSERT( all (not . isExistentialDataCon) cons )
558 newSysLocalDs record_in_ty `thenDs` \ case_bndr ->
559 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
560 mk_default `thenDs` \ deflt ->
562 returnDs (Case record_expr' case_bndr (alts ++ deflt))
564 has_all_fields :: DataCon -> Bool
565 has_all_fields con_id
568 con_fields = dataConFieldLabels con_id
569 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
572 Dictionary lambda and application
573 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
574 @DictLam@ and @DictApp@ turn into the regular old things.
575 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
576 complicated; reminiscent of fully-applied constructors.
578 dsExpr (DictLam dictvars expr)
579 = dsExpr expr `thenDs` \ core_expr ->
580 returnDs (mkLams dictvars core_expr)
584 dsExpr (DictApp expr dicts) -- becomes a curried application
585 = dsExpr expr `thenDs` \ core_expr ->
586 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
592 -- HsSyn constructs that just shouldn't be here:
593 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
594 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
595 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
596 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
599 out_of_range_msg -- ditto
600 = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
603 %--------------------------------------------------------------------
605 Basically does the translation given in the Haskell~1.3 report:
610 -> Id -- id for: return m
611 -> Id -- id for: (>>=) m
612 -> Id -- id for: fail m
613 -> Type -- Element type; the whole expression has type (m t)
616 dsDo do_or_lc stmts return_id then_id fail_id result_ty
618 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
621 = dsExpr expr `thenDs` \ expr2 ->
622 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
624 go (GuardStmt expr locn : stmts)
625 = do_expr expr locn `thenDs` \ expr2 ->
626 go stmts `thenDs` \ rest ->
627 let msg = ASSERT( isNotUsgTy b_ty )
628 "Pattern match failure in do expression, " ++ showSDoc (ppr locn) in
629 returnDs (mkIfThenElse expr2
631 (App (App (Var fail_id)
633 (mkLit (mkStrLit msg stringTy))))
635 go (ExprStmt expr locn : stmts)
636 = do_expr expr locn `thenDs` \ expr2 ->
638 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
643 go stmts `thenDs` \ rest ->
644 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
645 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
646 Lam ignored_result_id rest])
648 go (LetStmt binds : stmts )
649 = go stmts `thenDs` \ rest ->
652 go (BindStmt pat expr locn : stmts)
654 dsExpr expr `thenDs` \ expr2 ->
656 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
657 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty]) (HsLitOut (HsString (_PK_ msg)) stringTy)
658 msg = ASSERT2( isNotUsgTy a_ty, ppr a_ty )
659 ASSERT2( isNotUsgTy b_ty, ppr b_ty )
660 "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
661 main_match = mkSimpleMatch [pat]
662 (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty locn)
663 (Just result_ty) locn
665 | failureFreePat pat = [main_match]
668 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
671 matchWrapper DoBindMatch the_matches match_msg
672 `thenDs` \ (binders, matching_code) ->
673 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
674 mkLams binders matching_code])
679 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
681 match_msg = case do_or_lc of
682 DoStmt -> "`do' statement"
683 ListComp -> "comprehension"
687 var_pat (WildPat _) = True
688 var_pat (VarPat _) = True