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,
21 import CoreUtils ( exprType, mkIfThenElse, bindNonRec )
24 import DsBinds ( dsMonoBinds, AutoScc(..) )
25 import DsGRHSs ( dsGuarded )
26 import DsCCall ( dsCCall, resultWrapper )
27 import DsListComp ( dsListComp )
28 import DsUtils ( mkErrorAppDs, mkDsLets, mkStringLit, mkStringLitFS,
29 mkConsExpr, mkNilExpr, mkIntegerLit
31 import Match ( matchWrapper, matchSimply )
33 import CostCentre ( mkUserCC )
34 import Id ( Id, idType, recordSelectorFieldLabel )
35 import PrelInfo ( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
36 import DataCon ( DataCon, dataConWrapId, dataConArgTys, dataConFieldLabels )
37 import DataCon ( isExistentialDataCon )
38 import Literal ( Literal(..) )
39 import Type ( splitFunTys,
40 splitAlgTyConApp, splitAlgTyConApp_maybe, splitTyConApp_maybe,
42 splitAppTy, isUnLiftedType, Type
44 import TysWiredIn ( tupleCon, listTyCon, charDataCon, intDataCon, isIntegerTy )
45 import BasicTypes ( RecFlag(..), Boxity(..) )
46 import Maybes ( maybeToBool )
47 import PrelNames ( hasKey, ratioTyConKey )
48 import Util ( zipEqual, zipWithEqual )
51 import Ratio ( numerator, denominator )
55 %************************************************************************
59 %************************************************************************
61 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
62 and transforming it into one for the let-bindings enclosing the body.
64 This may seem a bit odd, but (source) let bindings can contain unboxed
69 This must be transformed to a case expression and, if the type has
70 more than one constructor, may fail.
73 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
78 dsLet (ThenBinds b1 b2) body
79 = dsLet b2 body `thenDs` \ body' ->
82 -- Special case for bindings which bind unlifted variables
83 -- Silently ignore INLINE pragmas...
84 dsLet (MonoBind (AbsBinds [] [] binder_triples inlines
85 (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))
96 `thenDs` \ error_expr ->
97 matchSimply rhs PatBindMatch pat body' error_expr
99 result_ty = exprType 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, constructors, literals}
113 %************************************************************************
116 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
118 dsExpr (HsVar var) = returnDs (Var var)
119 dsExpr (HsIPVar var) = returnDs (Var var)
120 dsExpr (HsLit lit) = dsLit lit
121 -- HsOverLit has been gotten rid of by the type checker
123 dsExpr expr@(HsLam a_Match)
124 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
125 returnDs (mkLams binders matching_code)
127 dsExpr expr@(HsApp fun arg)
128 = dsExpr fun `thenDs` \ core_fun ->
129 dsExpr arg `thenDs` \ core_arg ->
130 returnDs (core_fun `App` core_arg)
134 Operator sections. At first it looks as if we can convert
143 But no! expr might be a redex, and we can lose laziness badly this
148 for example. So we convert instead to
150 let y = expr in \x -> op y x
152 If \tr{expr} is actually just a variable, say, then the simplifier
156 dsExpr (OpApp e1 op _ e2)
157 = dsExpr op `thenDs` \ core_op ->
158 -- for the type of y, we need the type of op's 2nd argument
159 dsExpr e1 `thenDs` \ x_core ->
160 dsExpr e2 `thenDs` \ y_core ->
161 returnDs (mkApps core_op [x_core, y_core])
163 dsExpr (SectionL expr op)
164 = dsExpr op `thenDs` \ core_op ->
165 -- for the type of y, we need the type of op's 2nd argument
167 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
169 dsExpr expr `thenDs` \ x_core ->
170 newSysLocalDs x_ty `thenDs` \ x_id ->
171 newSysLocalDs y_ty `thenDs` \ y_id ->
173 returnDs (bindNonRec x_id x_core $
174 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
176 -- dsExpr (SectionR op expr) -- \ x -> op x expr
177 dsExpr (SectionR op expr)
178 = dsExpr op `thenDs` \ core_op ->
179 -- for the type of x, we need the type of op's 2nd argument
181 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
183 dsExpr expr `thenDs` \ y_core ->
184 newSysLocalDs x_ty `thenDs` \ x_id ->
185 newSysLocalDs y_ty `thenDs` \ y_id ->
187 returnDs (bindNonRec y_id y_core $
188 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
190 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
191 = mapDs dsExpr args `thenDs` \ core_args ->
192 dsCCall lbl core_args may_gc is_asm result_ty
193 -- dsCCall does all the unboxification, etc.
195 dsExpr (HsSCC cc expr)
196 = dsExpr expr `thenDs` \ core_expr ->
197 getModuleDs `thenDs` \ mod_name ->
198 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
200 -- special case to handle unboxed tuple patterns.
202 dsExpr (HsCase discrim matches src_loc)
203 | all ubx_tuple_match matches
204 = putSrcLocDs src_loc $
205 dsExpr discrim `thenDs` \ core_discrim ->
206 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
207 case matching_code of
208 Case (Var x) bndr alts | x == discrim_var ->
209 returnDs (Case core_discrim bndr alts)
210 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
212 ubx_tuple_match (Match _ [TuplePat ps Unboxed] _ _) = True
213 ubx_tuple_match _ = False
215 dsExpr (HsCase discrim matches src_loc)
216 = putSrcLocDs src_loc $
217 dsExpr discrim `thenDs` \ core_discrim ->
218 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
219 returnDs (bindNonRec discrim_var core_discrim matching_code)
221 dsExpr (HsLet binds body)
222 = dsExpr body `thenDs` \ body' ->
225 dsExpr (HsWith expr binds)
226 = dsExpr expr `thenDs` \ expr' ->
227 foldlDs dsIPBind expr' binds
230 = dsExpr e `thenDs` \ e' ->
231 returnDs (Let (NonRec n e') body)
233 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
234 | maybeToBool maybe_list_comp
235 = -- Special case for list comprehensions
236 putSrcLocDs src_loc $
237 dsListComp stmts elt_ty
240 = putSrcLocDs src_loc $
241 dsDo do_or_lc stmts return_id then_id fail_id result_ty
244 = case (do_or_lc, splitTyConApp_maybe result_ty) of
245 (ListComp, Just (tycon, [elt_ty]))
249 -- We need the ListComp form to use deListComp (rather than the "do" form)
250 -- because the "return" in a do block is a call to "PrelBase.return", and
251 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
253 Just elt_ty = maybe_list_comp
255 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
256 = putSrcLocDs src_loc $
257 dsExpr guard_expr `thenDs` \ core_guard ->
258 dsExpr then_expr `thenDs` \ core_then ->
259 dsExpr else_expr `thenDs` \ core_else ->
260 returnDs (mkIfThenElse core_guard core_then core_else)
265 \underline{\bf Type lambda and application}
266 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
268 dsExpr (TyLam tyvars expr)
269 = dsExpr expr `thenDs` \ core_expr ->
270 returnDs (mkLams tyvars core_expr)
272 dsExpr (TyApp expr tys)
273 = dsExpr expr `thenDs` \ core_expr ->
274 returnDs (mkTyApps core_expr tys)
279 \underline{\bf Various data construction things}
280 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
282 dsExpr (ExplicitListOut ty xs)
285 go [] = returnDs (mkNilExpr ty)
286 go (x:xs) = dsExpr x `thenDs` \ core_x ->
287 go xs `thenDs` \ core_xs ->
288 ASSERT( isNotUsgTy ty )
289 returnDs (mkConsExpr ty core_x core_xs)
291 dsExpr (ExplicitTuple expr_list boxity)
292 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
293 returnDs (mkConApp (tupleCon boxity (length expr_list))
294 (map (Type . unUsgTy . exprType) core_exprs ++ core_exprs))
295 -- the above unUsgTy is *required* -- KSW 1999-04-07
297 dsExpr (ArithSeqOut expr (From from))
298 = dsExpr expr `thenDs` \ expr2 ->
299 dsExpr from `thenDs` \ from2 ->
300 returnDs (App expr2 from2)
302 dsExpr (ArithSeqOut expr (FromTo from two))
303 = dsExpr expr `thenDs` \ expr2 ->
304 dsExpr from `thenDs` \ from2 ->
305 dsExpr two `thenDs` \ two2 ->
306 returnDs (mkApps expr2 [from2, two2])
308 dsExpr (ArithSeqOut expr (FromThen from thn))
309 = dsExpr expr `thenDs` \ expr2 ->
310 dsExpr from `thenDs` \ from2 ->
311 dsExpr thn `thenDs` \ thn2 ->
312 returnDs (mkApps expr2 [from2, thn2])
314 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
315 = dsExpr expr `thenDs` \ expr2 ->
316 dsExpr from `thenDs` \ from2 ->
317 dsExpr thn `thenDs` \ thn2 ->
318 dsExpr two `thenDs` \ two2 ->
319 returnDs (mkApps expr2 [from2, thn2, two2])
323 \underline{\bf Record construction and update}
324 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
325 For record construction we do this (assuming T has three arguments)
329 let err = /\a -> recConErr a
330 T (recConErr t1 "M.lhs/230/op1")
332 (recConErr t1 "M.lhs/230/op3")
334 @recConErr@ then converts its arugment string into a proper message
335 before printing it as
337 M.lhs, line 230: missing field op1 was evaluated
340 We also handle @C{}@ as valid construction syntax for an unlabelled
341 constructor @C@, setting all of @C@'s fields to bottom.
344 dsExpr (RecordConOut data_con con_expr rbinds)
345 = dsExpr con_expr `thenDs` \ con_expr' ->
347 (arg_tys, _) = splitFunTys (exprType con_expr')
350 = case [rhs | (sel_id,rhs,_) <- rbinds,
351 lbl == recordSelectorFieldLabel sel_id] of
352 (rhs:rhss) -> ASSERT( null rhss )
354 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
355 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
357 labels = dataConFieldLabels data_con
361 then mapDs unlabelled_bottom arg_tys
362 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
363 `thenDs` \ con_args ->
365 returnDs (mkApps con_expr' con_args)
368 Record update is a little harder. Suppose we have the decl:
370 data T = T1 {op1, op2, op3 :: Int}
371 | T2 {op4, op2 :: Int}
374 Then we translate as follows:
380 T1 op1 _ op3 -> T1 op1 op2 op3
381 T2 op4 _ -> T2 op4 op2
382 other -> recUpdError "M.lhs/230"
384 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
385 RHSs, and do not generate a Core constructor application directly, because the constructor
386 might do some argument-evaluation first; and may have to throw away some
390 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
391 = getSrcLocDs `thenDs` \ src_loc ->
392 dsExpr record_expr `thenDs` \ record_expr' ->
394 -- Desugar the rbinds, and generate let-bindings if
395 -- necessary so that we don't lose sharing
398 record_in_ty = exprType record_expr'
399 (_, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
400 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
401 cons_to_upd = filter has_all_fields cons
403 mk_val_arg field old_arg_id
404 = case [rhs | (sel_id, rhs, _) <- rbinds,
405 field == recordSelectorFieldLabel sel_id] of
406 (rhs:rest) -> ASSERT(null rest) rhs
407 [] -> HsVar old_arg_id
410 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
411 -- This call to dataConArgTys won't work for existentials
413 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
414 (dataConFieldLabels con) arg_ids
415 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConWrapId con))
420 returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
425 -- Record stuff doesn't work for existentials
426 ASSERT( all (not . isExistentialDataCon) cons )
428 -- It's important to generate the match with matchWrapper,
429 -- and the right hand sides with applications of the wrapper Id
430 -- so that everything works when we are doing fancy unboxing on the
431 -- constructor aguments.
432 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
433 matchWrapper RecUpdMatch alts "record update" `thenDs` \ ([discrim_var], matching_code) ->
435 returnDs (bindNonRec discrim_var record_expr' matching_code)
438 has_all_fields :: DataCon -> Bool
439 has_all_fields con_id
442 con_fields = dataConFieldLabels con_id
443 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
448 \underline{\bf Dictionary lambda and application}
449 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
450 @DictLam@ and @DictApp@ turn into the regular old things.
451 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
452 complicated; reminiscent of fully-applied constructors.
454 dsExpr (DictLam dictvars expr)
455 = dsExpr expr `thenDs` \ core_expr ->
456 returnDs (mkLams dictvars core_expr)
460 dsExpr (DictApp expr dicts) -- becomes a curried application
461 = dsExpr expr `thenDs` \ core_expr ->
462 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
468 -- HsSyn constructs that just shouldn't be here:
469 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
470 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
471 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
472 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
477 %--------------------------------------------------------------------
479 Basically does the translation given in the Haskell~1.3 report:
484 -> Id -- id for: return m
485 -> Id -- id for: (>>=) m
486 -> Id -- id for: fail m
487 -> Type -- Element type; the whole expression has type (m t)
490 dsDo do_or_lc stmts return_id then_id fail_id result_ty
492 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
495 = dsExpr expr `thenDs` \ expr2 ->
496 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
498 go (GuardStmt expr locn : stmts)
499 = do_expr expr locn `thenDs` \ expr2 ->
500 go stmts `thenDs` \ rest ->
501 let msg = ASSERT( isNotUsgTy b_ty )
502 "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
504 mkStringLit msg `thenDs` \ core_msg ->
505 returnDs (mkIfThenElse expr2
507 (App (App (Var fail_id)
511 go (ExprStmt expr locn : stmts)
512 = do_expr expr locn `thenDs` \ expr2 ->
514 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
519 go stmts `thenDs` \ rest ->
520 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
521 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
522 Lam ignored_result_id rest])
524 go (LetStmt binds : stmts )
525 = go stmts `thenDs` \ rest ->
528 go (BindStmt pat expr locn : stmts)
530 dsExpr expr `thenDs` \ expr2 ->
532 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
533 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
534 (HsLit (HsString (_PK_ msg)))
535 msg = ASSERT2( isNotUsgTy a_ty, ppr a_ty )
536 ASSERT2( isNotUsgTy b_ty, ppr b_ty )
537 "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
538 main_match = mkSimpleMatch [pat]
539 (HsDoOut do_or_lc stmts return_id then_id
540 fail_id result_ty locn)
541 (Just result_ty) locn
543 | failureFreePat pat = [main_match]
546 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
549 matchWrapper DoBindMatch the_matches match_msg
550 `thenDs` \ (binders, matching_code) ->
551 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
552 mkLams binders matching_code])
557 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
559 match_msg = case do_or_lc of
560 DoStmt -> "`do' statement"
561 ListComp -> "comprehension"
565 %************************************************************************
567 \subsection[DsExpr-literals]{Literals}
569 %************************************************************************
571 We give int/float literals type @Integer@ and @Rational@, respectively.
572 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
575 ToDo: put in range checks for when converting ``@i@''
576 (or should that be in the typechecker?)
578 For numeric literals, we try to detect there use at a standard type
579 (@Int@, @Float@, etc.) are directly put in the right constructor.
580 [NB: down with the @App@ conversion.]
582 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
585 dsLit :: HsLit -> DsM CoreExpr
586 dsLit (HsChar c) = returnDs (mkConApp charDataCon [mkLit (MachChar c)])
587 dsLit (HsCharPrim c) = returnDs (mkLit (MachChar c))
588 dsLit (HsString str) = mkStringLitFS str
589 dsLit (HsStringPrim s) = returnDs (mkLit (MachStr s))
590 dsLit (HsInteger i) = mkIntegerLit i
591 dsLit (HsInt i) = returnDs (mkConApp intDataCon [mkIntLit i])
592 dsLit (HsIntPrim i) = returnDs (mkIntLit i)
593 dsLit (HsFloatPrim f) = returnDs (mkLit (MachFloat f))
594 dsLit (HsDoublePrim d) = returnDs (mkLit (MachDouble d))
595 dsLit (HsLitLit str ty)
596 = ASSERT( maybeToBool maybe_ty )
597 returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
599 (maybe_ty, wrap_fn) = resultWrapper ty
600 Just rep_ty = maybe_ty
603 = mkIntegerLit (numerator r) `thenDs` \ num ->
604 mkIntegerLit (denominator r) `thenDs` \ denom ->
605 returnDs (mkConApp ratio_data_con [Type integer_ty, num, denom])
607 (ratio_data_con, integer_ty)
608 = case (splitAlgTyConApp_maybe ty) of
609 Just (tycon, [i_ty], [con])
610 -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)
613 _ -> (panic "ratio_data_con", panic "integer_ty")