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,
23 import CoreUtils ( exprType, mkIfThenElse, bindNonRec )
26 import DsBinds ( dsMonoBinds, AutoScc(..) )
27 import DsGRHSs ( dsGuarded )
28 import DsCCall ( dsCCall )
29 import DsListComp ( dsListComp )
30 import DsUtils ( mkErrorAppDs, mkDsLets, mkConsExpr, mkNilExpr )
31 import Match ( matchWrapper, matchSimply )
33 import CostCentre ( mkUserCC )
34 import FieldLabel ( FieldLabel )
35 import Id ( Id, idType, recordSelectorFieldLabel )
36 import DataCon ( DataCon, dataConId, dataConTyCon, dataConArgTys, dataConFieldLabels )
37 import PrelInfo ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID, addr2IntegerId )
38 import TyCon ( isNewTyCon )
39 import DataCon ( isExistentialDataCon )
40 import Literal ( Literal(..), inIntRange )
41 import Type ( splitFunTys, mkTyConApp,
42 splitAlgTyConApp, splitAlgTyConApp_maybe, splitTyConApp_maybe,
44 splitAppTy, isUnLiftedType, Type
46 import TysWiredIn ( tupleCon, unboxedTupleCon,
48 charDataCon, charTy, stringTy,
49 smallIntegerDataCon, isIntegerTy
51 import BasicTypes ( RecFlag(..) )
52 import Maybes ( maybeToBool )
53 import Unique ( Uniquable(..), ratioTyConKey )
54 import Util ( zipEqual, zipWithEqual )
57 import Ratio ( numerator, denominator )
61 %************************************************************************
65 %************************************************************************
67 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
68 and transforming it into one for the let-bindings enclosing the body.
70 This may seem a bit odd, but (source) let bindings can contain unboxed
75 This must be transformed to a case expression and, if the type has
76 more than one constructor, may fail.
79 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
84 dsLet (ThenBinds b1 b2) body
85 = dsLet b2 body `thenDs` \ body' ->
88 -- Special case for bindings which bind unlifted variables
89 -- Silently ignore INLINE pragmas...
90 dsLet (MonoBind (AbsBinds [] [] binder_triples inlines
91 (PatMonoBind pat grhss loc)) sigs is_rec) body
92 | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
93 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
95 dsGuarded grhss `thenDs` \ rhs ->
97 body' = foldr bind body binder_triples
98 bind (tyvars, g, l) body = ASSERT( null tyvars )
99 bindNonRec g (Var l) body
101 mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat))
102 `thenDs` \ error_expr ->
103 matchSimply rhs PatBindMatch pat body' error_expr
105 result_ty = exprType body
107 -- Ordinary case for bindings
108 dsLet (MonoBind binds sigs is_rec) body
109 = dsMonoBinds NoSccs binds [] `thenDs` \ prs ->
111 Recursive -> returnDs (Let (Rec prs) body)
112 NonRecursive -> returnDs (mkDsLets [NonRec b r | (b,r) <- prs] body)
115 %************************************************************************
117 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
119 %************************************************************************
122 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
124 dsExpr e@(HsVar var) = returnDs (Var var)
125 dsExpr e@(HsIPVar var) = returnDs (Var var)
128 %************************************************************************
130 \subsection[DsExpr-literals]{Literals}
132 %************************************************************************
134 We give int/float literals type @Integer@ and @Rational@, respectively.
135 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
138 ToDo: put in range checks for when converting ``@i@''
139 (or should that be in the typechecker?)
141 For numeric literals, we try to detect there use at a standard type
142 (@Int@, @Float@, etc.) are directly put in the right constructor.
143 [NB: down with the @App@ conversion.]
145 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
148 dsExpr (HsLitOut (HsString s) _)
150 = returnDs (mkNilExpr charTy)
154 the_char = mkConApp charDataCon [mkLit (MachChar (_HEAD_ s))]
155 the_nil = mkNilExpr charTy
156 the_cons = mkConsExpr charTy the_char the_nil
161 -- "_" => build (\ c n -> c 'c' n) -- LATER
163 dsExpr (HsLitOut (HsString str) _)
164 = returnDs (mkStringLitFS str)
166 dsExpr (HsLitOut (HsLitLit str) ty)
168 = returnDs (mkLit (MachLitLit str ty))
170 = case (maybeBoxedPrimType ty) of
171 Just (boxing_data_con, prim_ty) ->
172 returnDs ( mkConApp boxing_data_con [mkLit (MachLitLit str prim_ty)] )
176 [ hcat [ text "Cannot see data constructor of ``literal-literal''s type: "
177 , text "value:", quotes (quotes (ptext str))
178 , text "; type: ", ppr ty
180 , text "Try compiling with -fno-prune-tydecls."
185 = case (maybeBoxedPrimType ty) of
186 Just (boxing_data_con, prim_ty) -> (boxing_data_con, prim_ty)
188 -> pprPanic "ERROR: ``literal-literal'' not a single-constructor type: "
189 (hcat [ptext str, text "; type: ", ppr ty])
191 dsExpr (HsLitOut (HsInt i) ty)
192 = returnDs (mkIntegerLit i)
195 dsExpr (HsLitOut (HsFrac r) ty)
196 = returnDs (mkConApp ratio_data_con [Type integer_ty,
197 mkIntegerLit (numerator r),
198 mkIntegerLit (denominator r)])
200 (ratio_data_con, integer_ty)
201 = case (splitAlgTyConApp_maybe ty) of
202 Just (tycon, [i_ty], [con])
203 -> ASSERT(isIntegerTy i_ty && getUnique tycon == ratioTyConKey)
206 _ -> (panic "ratio_data_con", panic "integer_ty")
210 -- others where we know what to do:
212 dsExpr (HsLitOut (HsIntPrim i) _)
213 = returnDs (mkIntLit i)
215 dsExpr (HsLitOut (HsFloatPrim f) _)
216 = returnDs (mkLit (MachFloat f))
218 dsExpr (HsLitOut (HsDoublePrim d) _)
219 = returnDs (mkLit (MachDouble d))
220 -- ToDo: range checking needed!
222 dsExpr (HsLitOut (HsChar c) _)
223 = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
225 dsExpr (HsLitOut (HsCharPrim c) _)
226 = returnDs (mkLit (MachChar c))
228 dsExpr (HsLitOut (HsStringPrim s) _)
229 = returnDs (mkLit (MachStr s))
231 -- end of literals magic. --
233 dsExpr expr@(HsLam a_Match)
234 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
235 returnDs (mkLams binders matching_code)
237 dsExpr expr@(HsApp fun arg)
238 = dsExpr fun `thenDs` \ core_fun ->
239 dsExpr arg `thenDs` \ core_arg ->
240 returnDs (core_fun `App` core_arg)
244 Operator sections. At first it looks as if we can convert
253 But no! expr might be a redex, and we can lose laziness badly this
258 for example. So we convert instead to
260 let y = expr in \x -> op y x
262 If \tr{expr} is actually just a variable, say, then the simplifier
266 dsExpr (OpApp e1 op _ e2)
267 = dsExpr op `thenDs` \ core_op ->
268 -- for the type of y, we need the type of op's 2nd argument
269 dsExpr e1 `thenDs` \ x_core ->
270 dsExpr e2 `thenDs` \ y_core ->
271 returnDs (mkApps core_op [x_core, y_core])
273 dsExpr (SectionL expr op)
274 = dsExpr op `thenDs` \ core_op ->
275 -- for the type of y, we need the type of op's 2nd argument
277 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
279 dsExpr expr `thenDs` \ x_core ->
280 newSysLocalDs x_ty `thenDs` \ x_id ->
281 newSysLocalDs y_ty `thenDs` \ y_id ->
283 returnDs (bindNonRec x_id x_core $
284 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
286 -- dsExpr (SectionR op expr) -- \ x -> op x expr
287 dsExpr (SectionR op expr)
288 = dsExpr op `thenDs` \ core_op ->
289 -- for the type of x, we need the type of op's 2nd argument
291 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
293 dsExpr expr `thenDs` \ y_core ->
294 newSysLocalDs x_ty `thenDs` \ x_id ->
295 newSysLocalDs y_ty `thenDs` \ y_id ->
297 returnDs (bindNonRec y_id y_core $
298 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
300 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
301 = mapDs dsExpr args `thenDs` \ core_args ->
302 dsCCall lbl core_args may_gc is_asm result_ty
303 -- dsCCall does all the unboxification, etc.
305 dsExpr (HsSCC cc expr)
306 = dsExpr expr `thenDs` \ core_expr ->
307 getModuleDs `thenDs` \ mod_name ->
308 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
310 -- special case to handle unboxed tuple patterns.
312 dsExpr (HsCase discrim matches src_loc)
313 | all ubx_tuple_match matches
314 = putSrcLocDs src_loc $
315 dsExpr discrim `thenDs` \ core_discrim ->
316 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
317 case matching_code of
318 Case (Var x) bndr alts | x == discrim_var ->
319 returnDs (Case core_discrim bndr alts)
320 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
322 ubx_tuple_match (Match _ [TuplePat ps False{-unboxed-}] _ _) = True
323 ubx_tuple_match _ = False
325 dsExpr (HsCase discrim matches src_loc)
326 = putSrcLocDs src_loc $
327 dsExpr discrim `thenDs` \ core_discrim ->
328 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
329 returnDs (bindNonRec discrim_var core_discrim matching_code)
331 dsExpr (HsLet binds body)
332 = dsExpr body `thenDs` \ body' ->
335 dsExpr (HsWith expr binds)
336 = dsExpr expr `thenDs` \ expr' ->
337 foldlDs dsIPBind expr' binds
340 = dsExpr e `thenDs` \ e' ->
341 returnDs (Let (NonRec n e') body)
343 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
344 | maybeToBool maybe_list_comp
345 = -- Special case for list comprehensions
346 putSrcLocDs src_loc $
347 dsListComp stmts elt_ty
350 = putSrcLocDs src_loc $
351 dsDo do_or_lc stmts return_id then_id fail_id result_ty
354 = case (do_or_lc, splitTyConApp_maybe result_ty) of
355 (ListComp, Just (tycon, [elt_ty]))
359 -- We need the ListComp form to use deListComp (rather than the "do" form)
360 -- because the "return" in a do block is a call to "PrelBase.return", and
361 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
363 Just elt_ty = maybe_list_comp
365 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
366 = putSrcLocDs src_loc $
367 dsExpr guard_expr `thenDs` \ core_guard ->
368 dsExpr then_expr `thenDs` \ core_then ->
369 dsExpr else_expr `thenDs` \ core_else ->
370 returnDs (mkIfThenElse core_guard core_then core_else)
375 \underline{\bf Type lambda and application}
376 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
378 dsExpr (TyLam tyvars expr)
379 = dsExpr expr `thenDs` \ core_expr ->
380 returnDs (mkLams tyvars core_expr)
382 dsExpr (TyApp expr tys)
383 = dsExpr expr `thenDs` \ core_expr ->
384 returnDs (mkTyApps core_expr tys)
389 \underline{\bf Various data construction things}
390 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
392 dsExpr (ExplicitListOut ty xs)
395 list_ty = mkListTy ty
397 go [] = returnDs (mkNilExpr ty)
398 go (x:xs) = dsExpr x `thenDs` \ core_x ->
399 go xs `thenDs` \ core_xs ->
400 ASSERT( isNotUsgTy ty )
401 returnDs (mkConsExpr 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 . unUsgTy . exprType) core_exprs ++ core_exprs))
409 -- the above unUsgTy is *required* -- KSW 1999-04-07
411 dsExpr (ArithSeqOut expr (From from))
412 = dsExpr expr `thenDs` \ expr2 ->
413 dsExpr from `thenDs` \ from2 ->
414 returnDs (App expr2 from2)
416 dsExpr (ArithSeqOut expr (FromTo from two))
417 = dsExpr expr `thenDs` \ expr2 ->
418 dsExpr from `thenDs` \ from2 ->
419 dsExpr two `thenDs` \ two2 ->
420 returnDs (mkApps expr2 [from2, two2])
422 dsExpr (ArithSeqOut expr (FromThen from thn))
423 = dsExpr expr `thenDs` \ expr2 ->
424 dsExpr from `thenDs` \ from2 ->
425 dsExpr thn `thenDs` \ thn2 ->
426 returnDs (mkApps expr2 [from2, thn2])
428 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
429 = dsExpr expr `thenDs` \ expr2 ->
430 dsExpr from `thenDs` \ from2 ->
431 dsExpr thn `thenDs` \ thn2 ->
432 dsExpr two `thenDs` \ two2 ->
433 returnDs (mkApps expr2 [from2, thn2, two2])
437 \underline{\bf Record construction and update}
438 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
439 For record construction we do this (assuming T has three arguments)
443 let err = /\a -> recConErr a
444 T (recConErr t1 "M.lhs/230/op1")
446 (recConErr t1 "M.lhs/230/op3")
448 @recConErr@ then converts its arugment string into a proper message
449 before printing it as
451 M.lhs, line 230: missing field op1 was evaluated
454 We also handle @C{}@ as valid construction syntax for an unlabelled
455 constructor @C@, setting all of @C@'s fields to bottom.
458 dsExpr (RecordConOut data_con con_expr rbinds)
459 = dsExpr con_expr `thenDs` \ con_expr' ->
461 (arg_tys, _) = splitFunTys (exprType con_expr')
464 = case [rhs | (sel_id,rhs,_) <- rbinds,
465 lbl == recordSelectorFieldLabel sel_id] of
466 (rhs:rhss) -> ASSERT( null rhss )
468 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
469 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
471 labels = dataConFieldLabels data_con
475 then mapDs unlabelled_bottom arg_tys
476 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
477 `thenDs` \ con_args ->
479 returnDs (mkApps con_expr' con_args)
482 Record update is a little harder. Suppose we have the decl:
484 data T = T1 {op1, op2, op3 :: Int}
485 | T2 {op4, op2 :: Int}
488 Then we translate as follows:
494 T1 op1 _ op3 -> T1 op1 op2 op3
495 T2 op4 _ -> T2 op4 op2
496 other -> recUpdError "M.lhs/230"
498 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
499 RHSs, and do not generate a Core constructor application directly, because the constructor
500 might do some argument-evaluation first; and may have to throw away some
504 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
505 = getSrcLocDs `thenDs` \ src_loc ->
506 dsExpr record_expr `thenDs` \ record_expr' ->
508 -- Desugar the rbinds, and generate let-bindings if
509 -- necessary so that we don't lose sharing
512 record_in_ty = exprType record_expr'
513 (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
514 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
515 cons_to_upd = filter has_all_fields cons
517 mk_val_arg field old_arg_id
518 = case [rhs | (sel_id, rhs, _) <- rbinds,
519 field == recordSelectorFieldLabel sel_id] of
520 (rhs:rest) -> ASSERT(null rest) rhs
521 [] -> HsVar old_arg_id
524 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
525 -- This call to dataConArgTys won't work for existentials
527 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
528 (dataConFieldLabels con) arg_ids
529 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConId con))
534 returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
539 -- Record stuff doesn't work for existentials
540 ASSERT( all (not . isExistentialDataCon) cons )
542 -- It's important to generate the match with matchWrapper,
543 -- and the right hand sides with applications of the wrapper Id
544 -- so that everything works when we are doing fancy unboxing on the
545 -- constructor aguments.
546 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
547 matchWrapper RecUpdMatch alts "record update" `thenDs` \ ([discrim_var], matching_code) ->
549 returnDs (bindNonRec discrim_var record_expr' matching_code)
552 has_all_fields :: DataCon -> Bool
553 has_all_fields con_id
556 con_fields = dataConFieldLabels con_id
557 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
562 \underline{\bf 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"
591 %--------------------------------------------------------------------
593 Basically does the translation given in the Haskell~1.3 report:
598 -> Id -- id for: return m
599 -> Id -- id for: (>>=) m
600 -> Id -- id for: fail m
601 -> Type -- Element type; the whole expression has type (m t)
604 dsDo do_or_lc stmts return_id then_id fail_id result_ty
606 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
609 = dsExpr expr `thenDs` \ expr2 ->
610 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
612 go (GuardStmt expr locn : stmts)
613 = do_expr expr locn `thenDs` \ expr2 ->
614 go stmts `thenDs` \ rest ->
615 let msg = ASSERT( isNotUsgTy b_ty )
616 "Pattern match failure in do expression, " ++ showSDoc (ppr locn) in
617 returnDs (mkIfThenElse expr2
619 (App (App (Var fail_id)
623 go (ExprStmt expr locn : stmts)
624 = do_expr expr locn `thenDs` \ expr2 ->
626 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
631 go stmts `thenDs` \ rest ->
632 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
633 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
634 Lam ignored_result_id rest])
636 go (LetStmt binds : stmts )
637 = go stmts `thenDs` \ rest ->
640 go (BindStmt pat expr locn : stmts)
642 dsExpr expr `thenDs` \ expr2 ->
644 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
645 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
646 (HsLitOut (HsString (_PK_ msg)) stringTy)
647 msg = ASSERT2( isNotUsgTy a_ty, ppr a_ty )
648 ASSERT2( isNotUsgTy b_ty, ppr b_ty )
649 "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
650 main_match = mkSimpleMatch [pat]
651 (HsDoOut do_or_lc stmts return_id then_id
652 fail_id result_ty locn)
653 (Just result_ty) locn
655 | failureFreePat pat = [main_match]
658 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
661 matchWrapper DoBindMatch the_matches match_msg
662 `thenDs` \ (binders, matching_code) ->
663 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
664 mkLams binders matching_code])
669 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
671 match_msg = case do_or_lc of
672 DoStmt -> "`do' statement"
673 ListComp -> "comprehension"
677 var_pat (WildPat _) = True
678 var_pat (VarPat _) = True
683 mkIntegerLit :: Integer -> CoreExpr
685 | inIntRange i -- Small enough, so start from an Int
686 = mkConApp smallIntegerDataCon [mkIntLit i]
688 | otherwise -- Big, so start from a string
689 = App (Var addr2IntegerId) (Lit (MachStr (_PK_ (show i))))