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 src_loc)
305 | all ubx_tuple_match matches
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 ubx_tuple_match (Match _ [TuplePat ps False{-unboxed-}] _ _) = True
315 ubx_tuple_match _ = False
317 dsExpr (HsCase discrim matches src_loc)
318 = putSrcLocDs src_loc $
319 dsExpr discrim `thenDs` \ core_discrim ->
320 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
321 returnDs (bindNonRec discrim_var core_discrim matching_code)
323 dsExpr (HsLet binds body)
324 = dsExpr body `thenDs` \ body' ->
327 dsExpr (HsWith expr binds)
328 = dsExpr expr `thenDs` \ expr' ->
329 foldlDs dsIPBind expr' binds
332 = dsExpr e `thenDs` \ e' ->
333 returnDs (Let (NonRec n e') body)
335 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
336 | maybeToBool maybe_list_comp
337 = -- Special case for list comprehensions
338 putSrcLocDs src_loc $
339 dsListComp stmts elt_ty
342 = putSrcLocDs src_loc $
343 dsDo do_or_lc stmts return_id then_id fail_id result_ty
346 = case (do_or_lc, splitTyConApp_maybe result_ty) of
347 (ListComp, Just (tycon, [elt_ty]))
351 -- We need the ListComp form to use deListComp (rather than the "do" form)
352 -- because the "return" in a do block is a call to "PrelBase.return", and
353 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
355 Just elt_ty = maybe_list_comp
357 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
358 = putSrcLocDs src_loc $
359 dsExpr guard_expr `thenDs` \ core_guard ->
360 dsExpr then_expr `thenDs` \ core_then ->
361 dsExpr else_expr `thenDs` \ core_else ->
362 returnDs (mkIfThenElse core_guard core_then core_else)
367 \underline{\bf Type lambda and application}
368 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
370 dsExpr (TyLam tyvars expr)
371 = dsExpr expr `thenDs` \ core_expr ->
372 returnDs (mkLams tyvars core_expr)
374 dsExpr (TyApp expr tys)
375 = dsExpr expr `thenDs` \ core_expr ->
376 returnDs (mkTyApps core_expr tys)
381 \underline{\bf Various data construction things}
382 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
384 dsExpr (ExplicitListOut ty xs)
387 list_ty = mkListTy ty
389 go [] = returnDs (mkNilExpr ty)
390 go (x:xs) = dsExpr x `thenDs` \ core_x ->
391 go xs `thenDs` \ core_xs ->
392 ASSERT( isNotUsgTy ty )
393 returnDs (mkConsExpr ty core_x core_xs)
395 dsExpr (ExplicitTuple expr_list boxed)
396 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
397 returnDs (mkConApp ((if boxed
399 else unboxedTupleCon) (length expr_list))
400 (map (Type . unUsgTy . coreExprType) core_exprs ++ core_exprs))
401 -- the above unUsgTy is *required* -- KSW 1999-04-07
403 dsExpr (HsCon con_id [ty] [arg])
405 = dsExpr arg `thenDs` \ arg' ->
406 returnDs (Note (Coerce result_ty (unUsgTy (coreExprType arg'))) arg')
408 result_ty = mkTyConApp tycon [ty]
409 tycon = dataConTyCon con_id
411 dsExpr (HsCon con_id tys args)
412 = mapDs dsExpr args `thenDs` \ args2 ->
413 ASSERT( all isNotUsgTy tys )
414 returnDs (mkConApp con_id (map Type tys ++ args2))
416 dsExpr (ArithSeqOut expr (From from))
417 = dsExpr expr `thenDs` \ expr2 ->
418 dsExpr from `thenDs` \ from2 ->
419 returnDs (App expr2 from2)
421 dsExpr (ArithSeqOut expr (FromTo from two))
422 = dsExpr expr `thenDs` \ expr2 ->
423 dsExpr from `thenDs` \ from2 ->
424 dsExpr two `thenDs` \ two2 ->
425 returnDs (mkApps expr2 [from2, two2])
427 dsExpr (ArithSeqOut expr (FromThen from thn))
428 = dsExpr expr `thenDs` \ expr2 ->
429 dsExpr from `thenDs` \ from2 ->
430 dsExpr thn `thenDs` \ thn2 ->
431 returnDs (mkApps expr2 [from2, thn2])
433 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
434 = dsExpr expr `thenDs` \ expr2 ->
435 dsExpr from `thenDs` \ from2 ->
436 dsExpr thn `thenDs` \ thn2 ->
437 dsExpr two `thenDs` \ two2 ->
438 returnDs (mkApps expr2 [from2, thn2, two2])
442 \underline{\bf Record construction and update}
443 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
444 For record construction we do this (assuming T has three arguments)
448 let err = /\a -> recConErr a
449 T (recConErr t1 "M.lhs/230/op1")
451 (recConErr t1 "M.lhs/230/op3")
453 @recConErr@ then converts its arugment string into a proper message
454 before printing it as
456 M.lhs, line 230: missing field op1 was evaluated
459 We also handle @C{}@ as valid construction syntax for an unlabelled
460 constructor @C@, setting all of @C@'s fields to bottom.
463 dsExpr (RecordConOut data_con con_expr rbinds)
464 = dsExpr con_expr `thenDs` \ con_expr' ->
466 (arg_tys, _) = splitFunTys (coreExprType con_expr')
469 = case [rhs | (sel_id,rhs,_) <- rbinds,
470 lbl == recordSelectorFieldLabel sel_id] of
471 (rhs:rhss) -> ASSERT( null rhss )
473 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
474 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
476 labels = dataConFieldLabels data_con
480 then mapDs unlabelled_bottom arg_tys
481 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
482 `thenDs` \ con_args ->
484 returnDs (mkApps con_expr' con_args)
487 Record update is a little harder. Suppose we have the decl:
489 data T = T1 {op1, op2, op3 :: Int}
490 | T2 {op4, op2 :: Int}
493 Then we translate as follows:
499 T1 op1 _ op3 -> T1 op1 op2 op3
500 T2 op4 _ -> T2 op4 op2
501 other -> recUpdError "M.lhs/230"
503 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
504 RHSs, and do not generate a Core @Con@ directly, because the constructor
505 might do some argument-evaluation first; and may have to throw away some
509 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
510 = dsExpr record_expr `thenDs` \ record_expr' ->
512 -- Desugar the rbinds, and generate let-bindings if
513 -- necessary so that we don't lose sharing
516 ds_rbind (sel_id, rhs, pun_flag)
517 = dsExpr rhs `thenDs` \ rhs' ->
518 returnDs (recordSelectorFieldLabel sel_id, rhs')
520 mapDs ds_rbind rbinds `thenDs` \ rbinds' ->
522 record_in_ty = coreExprType record_expr'
523 (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
524 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
525 cons_to_upd = filter has_all_fields cons
527 -- initial_args are passed to every constructor
528 initial_args = map Type out_inst_tys ++ map Var dicts
530 mk_val_arg field old_arg_id
531 = case [rhs | (f, rhs) <- rbinds', field == f] of
532 (rhs:rest) -> ASSERT(null rest) rhs
536 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
537 -- This call to dataConArgTys won't work for existentials
539 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
540 (dataConFieldLabels con) arg_ids
541 rhs = mkApps (mkApps (Var (dataConId con)) initial_args) val_args
543 returnDs (DataCon con, arg_ids, rhs)
546 | length cons_to_upd == length cons
549 = mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty "" `thenDs` \ err ->
550 returnDs [(DEFAULT, [], err)]
552 -- Record stuff doesn't work for existentials
553 ASSERT( all (not . isExistentialDataCon) cons )
555 newSysLocalDs record_in_ty `thenDs` \ case_bndr ->
556 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
557 mk_default `thenDs` \ deflt ->
559 returnDs (Case record_expr' case_bndr (alts ++ deflt))
561 has_all_fields :: DataCon -> Bool
562 has_all_fields con_id
565 con_fields = dataConFieldLabels con_id
566 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
571 \underline{\bf Dictionary lambda and application}
572 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
573 @DictLam@ and @DictApp@ turn into the regular old things.
574 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
575 complicated; reminiscent of fully-applied constructors.
577 dsExpr (DictLam dictvars expr)
578 = dsExpr expr `thenDs` \ core_expr ->
579 returnDs (mkLams dictvars core_expr)
583 dsExpr (DictApp expr dicts) -- becomes a curried application
584 = dsExpr expr `thenDs` \ core_expr ->
585 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
591 -- HsSyn constructs that just shouldn't be here:
592 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
593 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
594 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
595 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
598 out_of_range_msg -- ditto
599 = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
602 %--------------------------------------------------------------------
604 Basically does the translation given in the Haskell~1.3 report:
609 -> Id -- id for: return m
610 -> Id -- id for: (>>=) m
611 -> Id -- id for: fail m
612 -> Type -- Element type; the whole expression has type (m t)
615 dsDo do_or_lc stmts return_id then_id fail_id result_ty
617 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
620 = dsExpr expr `thenDs` \ expr2 ->
621 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
623 go (GuardStmt expr locn : stmts)
624 = do_expr expr locn `thenDs` \ expr2 ->
625 go stmts `thenDs` \ rest ->
626 let msg = ASSERT( isNotUsgTy b_ty )
627 "Pattern match failure in do expression, " ++ showSDoc (ppr locn) in
628 returnDs (mkIfThenElse expr2
630 (App (App (Var fail_id)
632 (mkLit (mkStrLit msg stringTy))))
634 go (ExprStmt expr locn : stmts)
635 = do_expr expr locn `thenDs` \ expr2 ->
637 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
642 go stmts `thenDs` \ rest ->
643 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
644 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
645 Lam ignored_result_id rest])
647 go (LetStmt binds : stmts )
648 = go stmts `thenDs` \ rest ->
651 go (BindStmt pat expr locn : stmts)
653 dsExpr expr `thenDs` \ expr2 ->
655 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
656 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
657 (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
663 fail_id result_ty locn)
664 (Just result_ty) locn
666 | failureFreePat pat = [main_match]
669 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
672 matchWrapper DoBindMatch the_matches match_msg
673 `thenDs` \ (binders, matching_code) ->
674 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
675 mkLams binders matching_code])
680 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
682 match_msg = case do_or_lc of
683 DoStmt -> "`do' statement"
684 ListComp -> "comprehension"
688 var_pat (WildPat _) = True
689 var_pat (VarPat _) = True