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,
41 splitAppTy, isUnLiftedType, Type
43 import TysWiredIn ( tupleCon, listTyCon, charDataCon, intDataCon, isIntegerTy )
44 import BasicTypes ( RecFlag(..), Boxity(..) )
45 import Maybes ( maybeToBool )
46 import PrelNames ( hasKey, ratioTyConKey )
47 import Util ( zipEqual, zipWithEqual )
50 import Ratio ( numerator, denominator )
54 %************************************************************************
58 %************************************************************************
60 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
61 and transforming it into one for the let-bindings enclosing the body.
63 This may seem a bit odd, but (source) let bindings can contain unboxed
68 This must be transformed to a case expression and, if the type has
69 more than one constructor, may fail.
72 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
77 dsLet (ThenBinds b1 b2) body
78 = dsLet b2 body `thenDs` \ body' ->
81 -- Special case for bindings which bind unlifted variables
82 -- Silently ignore INLINE pragmas...
83 dsLet (MonoBind (AbsBinds [] [] binder_triples inlines
84 (PatMonoBind pat grhss loc)) sigs is_rec) body
85 | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
86 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
88 dsGuarded grhss `thenDs` \ rhs ->
90 body' = foldr bind body binder_triples
91 bind (tyvars, g, l) body = ASSERT( null tyvars )
92 bindNonRec g (Var l) body
94 mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat))
95 `thenDs` \ error_expr ->
96 matchSimply rhs PatBindMatch pat body' error_expr
98 result_ty = exprType body
100 -- Ordinary case for bindings
101 dsLet (MonoBind binds sigs is_rec) body
102 = dsMonoBinds NoSccs binds [] `thenDs` \ prs ->
104 Recursive -> returnDs (Let (Rec prs) body)
105 NonRecursive -> returnDs (mkDsLets [NonRec b r | (b,r) <- prs] body)
108 %************************************************************************
110 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
112 %************************************************************************
115 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
117 dsExpr (HsVar var) = returnDs (Var var)
118 dsExpr (HsIPVar var) = returnDs (Var var)
119 dsExpr (HsLit lit) = dsLit lit
120 -- HsOverLit has been gotten rid of by the type checker
122 dsExpr expr@(HsLam a_Match)
123 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
124 returnDs (mkLams binders matching_code)
126 dsExpr expr@(HsApp fun arg)
127 = dsExpr fun `thenDs` \ core_fun ->
128 dsExpr arg `thenDs` \ core_arg ->
129 returnDs (core_fun `App` core_arg)
133 Operator sections. At first it looks as if we can convert
142 But no! expr might be a redex, and we can lose laziness badly this
147 for example. So we convert instead to
149 let y = expr in \x -> op y x
151 If \tr{expr} is actually just a variable, say, then the simplifier
155 dsExpr (OpApp e1 op _ e2)
156 = dsExpr op `thenDs` \ core_op ->
157 -- for the type of y, we need the type of op's 2nd argument
158 dsExpr e1 `thenDs` \ x_core ->
159 dsExpr e2 `thenDs` \ y_core ->
160 returnDs (mkApps core_op [x_core, y_core])
162 dsExpr (SectionL expr op)
163 = dsExpr op `thenDs` \ core_op ->
164 -- for the type of y, we need the type of op's 2nd argument
166 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
168 dsExpr expr `thenDs` \ x_core ->
169 newSysLocalDs x_ty `thenDs` \ x_id ->
170 newSysLocalDs y_ty `thenDs` \ y_id ->
172 returnDs (bindNonRec x_id x_core $
173 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
175 -- dsExpr (SectionR op expr) -- \ x -> op x expr
176 dsExpr (SectionR op expr)
177 = dsExpr op `thenDs` \ core_op ->
178 -- for the type of x, we need the type of op's 2nd argument
180 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
182 dsExpr expr `thenDs` \ y_core ->
183 newSysLocalDs x_ty `thenDs` \ x_id ->
184 newSysLocalDs y_ty `thenDs` \ y_id ->
186 returnDs (bindNonRec y_id y_core $
187 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
189 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
190 = mapDs dsExpr args `thenDs` \ core_args ->
191 dsCCall lbl core_args may_gc is_asm result_ty
192 -- dsCCall does all the unboxification, etc.
194 dsExpr (HsSCC cc expr)
195 = dsExpr expr `thenDs` \ core_expr ->
196 getModuleDs `thenDs` \ mod_name ->
197 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
199 -- special case to handle unboxed tuple patterns.
201 dsExpr (HsCase discrim matches src_loc)
202 | all ubx_tuple_match matches
203 = putSrcLocDs src_loc $
204 dsExpr discrim `thenDs` \ core_discrim ->
205 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
206 case matching_code of
207 Case (Var x) bndr alts | x == discrim_var ->
208 returnDs (Case core_discrim bndr alts)
209 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
211 ubx_tuple_match (Match _ [TuplePat ps Unboxed] _ _) = True
212 ubx_tuple_match _ = False
214 dsExpr (HsCase discrim matches src_loc)
215 = putSrcLocDs src_loc $
216 dsExpr discrim `thenDs` \ core_discrim ->
217 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
218 returnDs (bindNonRec discrim_var core_discrim matching_code)
220 dsExpr (HsLet binds body)
221 = dsExpr body `thenDs` \ body' ->
224 dsExpr (HsWith expr binds)
225 = dsExpr expr `thenDs` \ expr' ->
226 foldlDs dsIPBind expr' binds
229 = dsExpr e `thenDs` \ e' ->
230 returnDs (Let (NonRec n e') body)
232 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
233 | maybeToBool maybe_list_comp
234 = -- Special case for list comprehensions
235 putSrcLocDs src_loc $
236 dsListComp stmts elt_ty
239 = putSrcLocDs src_loc $
240 dsDo do_or_lc stmts return_id then_id fail_id result_ty
243 = case (do_or_lc, splitTyConApp_maybe result_ty) of
244 (ListComp, Just (tycon, [elt_ty]))
248 -- We need the ListComp form to use deListComp (rather than the "do" form)
249 -- because the "return" in a do block is a call to "PrelBase.return", and
250 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
252 Just elt_ty = maybe_list_comp
254 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
255 = putSrcLocDs src_loc $
256 dsExpr guard_expr `thenDs` \ core_guard ->
257 dsExpr then_expr `thenDs` \ core_then ->
258 dsExpr else_expr `thenDs` \ core_else ->
259 returnDs (mkIfThenElse core_guard core_then core_else)
264 \underline{\bf Type lambda and application}
265 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
267 dsExpr (TyLam tyvars expr)
268 = dsExpr expr `thenDs` \ core_expr ->
269 returnDs (mkLams tyvars core_expr)
271 dsExpr (TyApp expr tys)
272 = dsExpr expr `thenDs` \ core_expr ->
273 returnDs (mkTyApps core_expr tys)
278 \underline{\bf Various data construction things}
279 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
281 dsExpr (ExplicitListOut ty xs)
284 go [] = returnDs (mkNilExpr ty)
285 go (x:xs) = dsExpr x `thenDs` \ core_x ->
286 go xs `thenDs` \ core_xs ->
287 returnDs (mkConsExpr ty core_x core_xs)
289 dsExpr (ExplicitTuple expr_list boxity)
290 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
291 returnDs (mkConApp (tupleCon boxity (length expr_list))
292 (map (Type . exprType) core_exprs ++ core_exprs))
294 dsExpr (ArithSeqOut expr (From from))
295 = dsExpr expr `thenDs` \ expr2 ->
296 dsExpr from `thenDs` \ from2 ->
297 returnDs (App expr2 from2)
299 dsExpr (ArithSeqOut expr (FromTo from two))
300 = dsExpr expr `thenDs` \ expr2 ->
301 dsExpr from `thenDs` \ from2 ->
302 dsExpr two `thenDs` \ two2 ->
303 returnDs (mkApps expr2 [from2, two2])
305 dsExpr (ArithSeqOut expr (FromThen from thn))
306 = dsExpr expr `thenDs` \ expr2 ->
307 dsExpr from `thenDs` \ from2 ->
308 dsExpr thn `thenDs` \ thn2 ->
309 returnDs (mkApps expr2 [from2, thn2])
311 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
312 = dsExpr expr `thenDs` \ expr2 ->
313 dsExpr from `thenDs` \ from2 ->
314 dsExpr thn `thenDs` \ thn2 ->
315 dsExpr two `thenDs` \ two2 ->
316 returnDs (mkApps expr2 [from2, thn2, two2])
320 \underline{\bf Record construction and update}
321 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
322 For record construction we do this (assuming T has three arguments)
326 let err = /\a -> recConErr a
327 T (recConErr t1 "M.lhs/230/op1")
329 (recConErr t1 "M.lhs/230/op3")
331 @recConErr@ then converts its arugment string into a proper message
332 before printing it as
334 M.lhs, line 230: missing field op1 was evaluated
337 We also handle @C{}@ as valid construction syntax for an unlabelled
338 constructor @C@, setting all of @C@'s fields to bottom.
341 dsExpr (RecordConOut data_con con_expr rbinds)
342 = dsExpr con_expr `thenDs` \ con_expr' ->
344 (arg_tys, _) = splitFunTys (exprType con_expr')
347 = case [rhs | (sel_id,rhs,_) <- rbinds,
348 lbl == recordSelectorFieldLabel sel_id] of
349 (rhs:rhss) -> ASSERT( null rhss )
351 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
352 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
354 labels = dataConFieldLabels data_con
358 then mapDs unlabelled_bottom arg_tys
359 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
360 `thenDs` \ con_args ->
362 returnDs (mkApps con_expr' con_args)
365 Record update is a little harder. Suppose we have the decl:
367 data T = T1 {op1, op2, op3 :: Int}
368 | T2 {op4, op2 :: Int}
371 Then we translate as follows:
377 T1 op1 _ op3 -> T1 op1 op2 op3
378 T2 op4 _ -> T2 op4 op2
379 other -> recUpdError "M.lhs/230"
381 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
382 RHSs, and do not generate a Core constructor application directly, because the constructor
383 might do some argument-evaluation first; and may have to throw away some
387 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
388 = getSrcLocDs `thenDs` \ src_loc ->
389 dsExpr record_expr `thenDs` \ record_expr' ->
391 -- Desugar the rbinds, and generate let-bindings if
392 -- necessary so that we don't lose sharing
395 record_in_ty = exprType record_expr'
396 (_, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
397 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
398 cons_to_upd = filter has_all_fields cons
400 mk_val_arg field old_arg_id
401 = case [rhs | (sel_id, rhs, _) <- rbinds,
402 field == recordSelectorFieldLabel sel_id] of
403 (rhs:rest) -> ASSERT(null rest) rhs
404 [] -> HsVar old_arg_id
407 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
408 -- This call to dataConArgTys won't work for existentials
410 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
411 (dataConFieldLabels con) arg_ids
412 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConWrapId con))
417 returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
422 -- Record stuff doesn't work for existentials
423 ASSERT( all (not . isExistentialDataCon) cons )
425 -- It's important to generate the match with matchWrapper,
426 -- and the right hand sides with applications of the wrapper Id
427 -- so that everything works when we are doing fancy unboxing on the
428 -- constructor aguments.
429 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
430 matchWrapper RecUpdMatch alts "record update" `thenDs` \ ([discrim_var], matching_code) ->
432 returnDs (bindNonRec discrim_var record_expr' matching_code)
435 has_all_fields :: DataCon -> Bool
436 has_all_fields con_id
439 con_fields = dataConFieldLabels con_id
440 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
445 \underline{\bf Dictionary lambda and application}
446 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
447 @DictLam@ and @DictApp@ turn into the regular old things.
448 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
449 complicated; reminiscent of fully-applied constructors.
451 dsExpr (DictLam dictvars expr)
452 = dsExpr expr `thenDs` \ core_expr ->
453 returnDs (mkLams dictvars core_expr)
457 dsExpr (DictApp expr dicts) -- becomes a curried application
458 = dsExpr expr `thenDs` \ core_expr ->
459 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
465 -- HsSyn constructs that just shouldn't be here:
466 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
467 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
468 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
469 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
474 %--------------------------------------------------------------------
476 Basically does the translation given in the Haskell~1.3 report:
481 -> Id -- id for: return m
482 -> Id -- id for: (>>=) m
483 -> Id -- id for: fail m
484 -> Type -- Element type; the whole expression has type (m t)
487 dsDo do_or_lc stmts return_id then_id fail_id result_ty
489 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
492 = dsExpr expr `thenDs` \ expr2 ->
493 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
495 go (GuardStmt expr locn : stmts)
496 = do_expr expr locn `thenDs` \ expr2 ->
497 go stmts `thenDs` \ rest ->
498 let msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
500 mkStringLit msg `thenDs` \ core_msg ->
501 returnDs (mkIfThenElse expr2
503 (App (App (Var fail_id)
507 go (ExprStmt expr locn : stmts)
508 = do_expr expr locn `thenDs` \ expr2 ->
510 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
515 go stmts `thenDs` \ rest ->
516 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
517 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
518 Lam ignored_result_id rest])
520 go (LetStmt binds : stmts )
521 = go stmts `thenDs` \ rest ->
524 go (BindStmt pat expr locn : stmts)
526 dsExpr expr `thenDs` \ expr2 ->
528 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
529 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
530 (HsLit (HsString (_PK_ msg)))
531 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
532 main_match = mkSimpleMatch [pat]
533 (HsDoOut do_or_lc stmts return_id then_id
534 fail_id result_ty locn)
535 (Just result_ty) locn
537 | failureFreePat pat = [main_match]
540 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
543 matchWrapper DoBindMatch the_matches match_msg
544 `thenDs` \ (binders, matching_code) ->
545 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
546 mkLams binders matching_code])
551 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
553 match_msg = case do_or_lc of
554 DoStmt -> "`do' statement"
555 ListComp -> "comprehension"
559 %************************************************************************
561 \subsection[DsExpr-literals]{Literals}
563 %************************************************************************
565 We give int/float literals type @Integer@ and @Rational@, respectively.
566 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
569 ToDo: put in range checks for when converting ``@i@''
570 (or should that be in the typechecker?)
572 For numeric literals, we try to detect there use at a standard type
573 (@Int@, @Float@, etc.) are directly put in the right constructor.
574 [NB: down with the @App@ conversion.]
576 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
579 dsLit :: HsLit -> DsM CoreExpr
580 dsLit (HsChar c) = returnDs (mkConApp charDataCon [mkLit (MachChar c)])
581 dsLit (HsCharPrim c) = returnDs (mkLit (MachChar c))
582 dsLit (HsString str) = mkStringLitFS str
583 dsLit (HsStringPrim s) = returnDs (mkLit (MachStr s))
584 dsLit (HsInteger i) = mkIntegerLit i
585 dsLit (HsInt i) = returnDs (mkConApp intDataCon [mkIntLit i])
586 dsLit (HsIntPrim i) = returnDs (mkIntLit i)
587 dsLit (HsFloatPrim f) = returnDs (mkLit (MachFloat f))
588 dsLit (HsDoublePrim d) = returnDs (mkLit (MachDouble d))
589 dsLit (HsLitLit str ty)
590 = ASSERT( maybeToBool maybe_ty )
591 returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
593 (maybe_ty, wrap_fn) = resultWrapper ty
594 Just rep_ty = maybe_ty
597 = mkIntegerLit (numerator r) `thenDs` \ num ->
598 mkIntegerLit (denominator r) `thenDs` \ denom ->
599 returnDs (mkConApp ratio_data_con [Type integer_ty, num, denom])
601 (ratio_data_con, integer_ty)
602 = case (splitAlgTyConApp_maybe ty) of
603 Just (tycon, [i_ty], [con])
604 -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)
607 _ -> (panic "ratio_data_con", panic "integer_ty")