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 FieldLabel ( FieldLabel, fieldLabelTyCon )
34 import CostCentre ( mkUserCC )
35 import Id ( Id, idType, recordSelectorFieldLabel )
36 import PrelInfo ( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
37 import DataCon ( DataCon, dataConWrapId, dataConArgTys, dataConFieldLabels )
38 import DataCon ( isExistentialDataCon )
39 import Literal ( Literal(..) )
40 import TyCon ( tyConDataCons )
41 import Type ( splitFunTys,
42 splitAlgTyConApp, splitTyConApp_maybe, tyConAppArgs,
43 splitAppTy, isUnLiftedType, Type
45 import TysWiredIn ( tupleCon, listTyCon, charDataCon, intDataCon, isIntegerTy )
46 import BasicTypes ( RecFlag(..), Boxity(..) )
47 import Maybes ( maybeToBool )
48 import PrelNames ( hasKey, ratioTyConKey )
49 import Util ( zipEqual, zipWithEqual )
52 import Ratio ( numerator, denominator )
56 %************************************************************************
60 %************************************************************************
62 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
63 and transforming it into one for the let-bindings enclosing the body.
65 This may seem a bit odd, but (source) let bindings can contain unboxed
70 This must be transformed to a case expression and, if the type has
71 more than one constructor, may fail.
74 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
79 dsLet (ThenBinds b1 b2) body
80 = dsLet b2 body `thenDs` \ body' ->
83 -- Special case for bindings which bind unlifted variables
84 -- Silently ignore INLINE pragmas...
85 dsLet (MonoBind (AbsBinds [] [] binder_triples inlines
86 (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))
97 `thenDs` \ error_expr ->
98 matchSimply rhs PatBindMatch pat body' error_expr
100 result_ty = exprType body
102 -- Ordinary case for bindings
103 dsLet (MonoBind binds sigs is_rec) body
104 = dsMonoBinds NoSccs binds [] `thenDs` \ prs ->
106 Recursive -> returnDs (Let (Rec prs) body)
107 NonRecursive -> returnDs (mkDsLets [NonRec b r | (b,r) <- prs] body)
110 %************************************************************************
112 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
114 %************************************************************************
117 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
119 dsExpr (HsVar var) = returnDs (Var var)
120 dsExpr (HsIPVar var) = returnDs (Var var)
121 dsExpr (HsLit lit) = dsLit lit
122 -- HsOverLit has been gotten rid of by the type checker
124 dsExpr expr@(HsLam a_Match)
125 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
126 returnDs (mkLams binders matching_code)
128 dsExpr expr@(HsApp fun arg)
129 = dsExpr fun `thenDs` \ core_fun ->
130 dsExpr arg `thenDs` \ core_arg ->
131 returnDs (core_fun `App` core_arg)
135 Operator sections. At first it looks as if we can convert
144 But no! expr might be a redex, and we can lose laziness badly this
149 for example. So we convert instead to
151 let y = expr in \x -> op y x
153 If \tr{expr} is actually just a variable, say, then the simplifier
157 dsExpr (OpApp e1 op _ e2)
158 = dsExpr op `thenDs` \ core_op ->
159 -- for the type of y, we need the type of op's 2nd argument
160 dsExpr e1 `thenDs` \ x_core ->
161 dsExpr e2 `thenDs` \ y_core ->
162 returnDs (mkApps core_op [x_core, y_core])
164 dsExpr (SectionL expr op)
165 = dsExpr op `thenDs` \ core_op ->
166 -- for the type of y, we need the type of op's 2nd argument
168 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
170 dsExpr expr `thenDs` \ x_core ->
171 newSysLocalDs x_ty `thenDs` \ x_id ->
172 newSysLocalDs y_ty `thenDs` \ y_id ->
174 returnDs (bindNonRec x_id x_core $
175 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
177 -- dsExpr (SectionR op expr) -- \ x -> op x expr
178 dsExpr (SectionR op expr)
179 = dsExpr op `thenDs` \ core_op ->
180 -- for the type of x, we need the type of op's 2nd argument
182 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
184 dsExpr expr `thenDs` \ y_core ->
185 newSysLocalDs x_ty `thenDs` \ x_id ->
186 newSysLocalDs y_ty `thenDs` \ y_id ->
188 returnDs (bindNonRec y_id y_core $
189 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
191 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
192 = mapDs dsExpr args `thenDs` \ core_args ->
193 dsCCall lbl core_args may_gc is_asm result_ty
194 -- dsCCall does all the unboxification, etc.
196 dsExpr (HsSCC cc expr)
197 = dsExpr expr `thenDs` \ core_expr ->
198 getModuleDs `thenDs` \ mod_name ->
199 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
201 -- special case to handle unboxed tuple patterns.
203 dsExpr (HsCase discrim matches src_loc)
204 | all ubx_tuple_match matches
205 = putSrcLocDs src_loc $
206 dsExpr discrim `thenDs` \ core_discrim ->
207 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
208 case matching_code of
209 Case (Var x) bndr alts | x == discrim_var ->
210 returnDs (Case core_discrim bndr alts)
211 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
213 ubx_tuple_match (Match _ [TuplePat ps Unboxed] _ _) = True
214 ubx_tuple_match _ = False
216 dsExpr (HsCase discrim matches src_loc)
217 = putSrcLocDs src_loc $
218 dsExpr discrim `thenDs` \ core_discrim ->
219 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
220 returnDs (bindNonRec discrim_var core_discrim matching_code)
222 dsExpr (HsLet binds body)
223 = dsExpr body `thenDs` \ body' ->
226 dsExpr (HsWith expr binds)
227 = dsExpr expr `thenDs` \ expr' ->
228 foldlDs dsIPBind expr' binds
231 = dsExpr e `thenDs` \ e' ->
232 returnDs (Let (NonRec n e') body)
234 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
235 | maybeToBool maybe_list_comp
236 = -- Special case for list comprehensions
237 putSrcLocDs src_loc $
238 dsListComp stmts elt_ty
241 = putSrcLocDs src_loc $
242 dsDo do_or_lc stmts return_id then_id fail_id result_ty
245 = case (do_or_lc, splitTyConApp_maybe result_ty) of
246 (ListComp, Just (tycon, [elt_ty]))
250 -- We need the ListComp form to use deListComp (rather than the "do" form)
251 -- because the "return" in a do block is a call to "PrelBase.return", and
252 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
254 Just elt_ty = maybe_list_comp
256 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
257 = putSrcLocDs src_loc $
258 dsExpr guard_expr `thenDs` \ core_guard ->
259 dsExpr then_expr `thenDs` \ core_then ->
260 dsExpr else_expr `thenDs` \ core_else ->
261 returnDs (mkIfThenElse core_guard core_then core_else)
266 \underline{\bf Type lambda and application}
267 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
269 dsExpr (TyLam tyvars expr)
270 = dsExpr expr `thenDs` \ core_expr ->
271 returnDs (mkLams tyvars core_expr)
273 dsExpr (TyApp expr tys)
274 = dsExpr expr `thenDs` \ core_expr ->
275 returnDs (mkTyApps core_expr tys)
280 \underline{\bf Various data construction things}
281 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
283 dsExpr (ExplicitListOut ty xs)
286 go [] = returnDs (mkNilExpr ty)
287 go (x:xs) = dsExpr x `thenDs` \ core_x ->
288 go xs `thenDs` \ core_xs ->
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 . exprType) core_exprs ++ core_exprs))
296 dsExpr (ArithSeqOut expr (From from))
297 = dsExpr expr `thenDs` \ expr2 ->
298 dsExpr from `thenDs` \ from2 ->
299 returnDs (App expr2 from2)
301 dsExpr (ArithSeqOut expr (FromTo from two))
302 = dsExpr expr `thenDs` \ expr2 ->
303 dsExpr from `thenDs` \ from2 ->
304 dsExpr two `thenDs` \ two2 ->
305 returnDs (mkApps expr2 [from2, two2])
307 dsExpr (ArithSeqOut expr (FromThen from thn))
308 = dsExpr expr `thenDs` \ expr2 ->
309 dsExpr from `thenDs` \ from2 ->
310 dsExpr thn `thenDs` \ thn2 ->
311 returnDs (mkApps expr2 [from2, thn2])
313 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
314 = dsExpr expr `thenDs` \ expr2 ->
315 dsExpr from `thenDs` \ from2 ->
316 dsExpr thn `thenDs` \ thn2 ->
317 dsExpr two `thenDs` \ two2 ->
318 returnDs (mkApps expr2 [from2, thn2, two2])
322 \underline{\bf Record construction and update}
323 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
324 For record construction we do this (assuming T has three arguments)
328 let err = /\a -> recConErr a
329 T (recConErr t1 "M.lhs/230/op1")
331 (recConErr t1 "M.lhs/230/op3")
333 @recConErr@ then converts its arugment string into a proper message
334 before printing it as
336 M.lhs, line 230: missing field op1 was evaluated
339 We also handle @C{}@ as valid construction syntax for an unlabelled
340 constructor @C@, setting all of @C@'s fields to bottom.
343 dsExpr (RecordConOut data_con con_expr rbinds)
344 = dsExpr con_expr `thenDs` \ con_expr' ->
346 (arg_tys, _) = splitFunTys (exprType con_expr')
349 = case [rhs | (sel_id,rhs,_) <- rbinds,
350 lbl == recordSelectorFieldLabel sel_id] of
351 (rhs:rhss) -> ASSERT( null rhss )
353 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
354 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
356 labels = dataConFieldLabels data_con
360 then mapDs unlabelled_bottom arg_tys
361 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
362 `thenDs` \ con_args ->
364 returnDs (mkApps con_expr' con_args)
367 Record update is a little harder. Suppose we have the decl:
369 data T = T1 {op1, op2, op3 :: Int}
370 | T2 {op4, op2 :: Int}
373 Then we translate as follows:
379 T1 op1 _ op3 -> T1 op1 op2 op3
380 T2 op4 _ -> T2 op4 op2
381 other -> recUpdError "M.lhs/230"
383 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
384 RHSs, and do not generate a Core constructor application directly, because the constructor
385 might do some argument-evaluation first; and may have to throw away some
389 dsExpr (RecordUpdOut record_expr record_out_ty dicts [])
392 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
393 = getSrcLocDs `thenDs` \ src_loc ->
394 dsExpr record_expr `thenDs` \ record_expr' ->
396 -- Desugar the rbinds, and generate let-bindings if
397 -- necessary so that we don't lose sharing
400 record_in_ty = exprType record_expr'
401 in_inst_tys = tyConAppArgs record_in_ty
402 out_inst_tys = tyConAppArgs record_out_ty
404 mk_val_arg field old_arg_id
405 = case [rhs | (sel_id, rhs, _) <- rbinds,
406 field == recordSelectorFieldLabel sel_id] of
407 (rhs:rest) -> ASSERT(null rest) rhs
408 [] -> HsVar old_arg_id
411 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
412 -- This call to dataConArgTys won't work for existentials
414 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
415 (dataConFieldLabels con) arg_ids
416 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConWrapId con))
421 returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
426 -- Record stuff doesn't work for existentials
427 ASSERT( all (not . isExistentialDataCon) data_cons )
429 -- It's important to generate the match with matchWrapper,
430 -- and the right hand sides with applications of the wrapper Id
431 -- so that everything works when we are doing fancy unboxing on the
432 -- constructor aguments.
433 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
434 matchWrapper RecUpdMatch alts "record update" `thenDs` \ ([discrim_var], matching_code) ->
436 returnDs (bindNonRec discrim_var record_expr' matching_code)
439 updated_fields :: [FieldLabel]
440 updated_fields = [recordSelectorFieldLabel sel_id | (sel_id,_,_) <- rbinds]
442 -- Get the type constructor from the first field label,
443 -- so that we are sure it'll have all its DataCons
444 -- (In GHCI, it's possible that some TyCons may not have all
445 -- their constructors, in a module-loop situation.)
446 tycon = fieldLabelTyCon (head updated_fields)
447 data_cons = tyConDataCons tycon
448 cons_to_upd = filter has_all_fields data_cons
450 has_all_fields :: DataCon -> Bool
451 has_all_fields con_id
452 = all (`elem` con_fields) updated_fields
454 con_fields = dataConFieldLabels con_id
459 \underline{\bf Dictionary lambda and application}
460 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
461 @DictLam@ and @DictApp@ turn into the regular old things.
462 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
463 complicated; reminiscent of fully-applied constructors.
465 dsExpr (DictLam dictvars expr)
466 = dsExpr expr `thenDs` \ core_expr ->
467 returnDs (mkLams dictvars core_expr)
471 dsExpr (DictApp expr dicts) -- becomes a curried application
472 = dsExpr expr `thenDs` \ core_expr ->
473 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
479 -- HsSyn constructs that just shouldn't be here:
480 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
481 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
482 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
483 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
488 %--------------------------------------------------------------------
490 Basically does the translation given in the Haskell~1.3 report:
495 -> Id -- id for: return m
496 -> Id -- id for: (>>=) m
497 -> Id -- id for: fail m
498 -> Type -- Element type; the whole expression has type (m t)
501 dsDo do_or_lc stmts return_id then_id fail_id result_ty
503 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
506 = dsExpr expr `thenDs` \ expr2 ->
507 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
509 go (GuardStmt expr locn : stmts)
510 = do_expr expr locn `thenDs` \ expr2 ->
511 go stmts `thenDs` \ rest ->
512 let msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
514 mkStringLit msg `thenDs` \ core_msg ->
515 returnDs (mkIfThenElse expr2
517 (App (App (Var fail_id)
521 go (ExprStmt expr locn : stmts)
522 = do_expr expr locn `thenDs` \ expr2 ->
524 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
529 go stmts `thenDs` \ rest ->
530 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
531 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
532 Lam ignored_result_id rest])
534 go (LetStmt binds : stmts )
535 = go stmts `thenDs` \ rest ->
538 go (BindStmt pat expr locn : stmts)
540 dsExpr expr `thenDs` \ expr2 ->
542 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
543 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
544 (HsLit (HsString (_PK_ msg)))
545 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
546 main_match = mkSimpleMatch [pat]
547 (HsDoOut do_or_lc stmts return_id then_id
548 fail_id result_ty locn)
549 (Just result_ty) locn
551 | failureFreePat pat = [main_match]
554 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
557 matchWrapper DoBindMatch the_matches match_msg
558 `thenDs` \ (binders, matching_code) ->
559 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
560 mkLams binders matching_code])
565 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
567 match_msg = case do_or_lc of
568 DoStmt -> "`do' statement"
569 ListComp -> "comprehension"
573 %************************************************************************
575 \subsection[DsExpr-literals]{Literals}
577 %************************************************************************
579 We give int/float literals type @Integer@ and @Rational@, respectively.
580 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
583 ToDo: put in range checks for when converting ``@i@''
584 (or should that be in the typechecker?)
586 For numeric literals, we try to detect there use at a standard type
587 (@Int@, @Float@, etc.) are directly put in the right constructor.
588 [NB: down with the @App@ conversion.]
590 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
593 dsLit :: HsLit -> DsM CoreExpr
594 dsLit (HsChar c) = returnDs (mkConApp charDataCon [mkLit (MachChar c)])
595 dsLit (HsCharPrim c) = returnDs (mkLit (MachChar c))
596 dsLit (HsString str) = mkStringLitFS str
597 dsLit (HsStringPrim s) = returnDs (mkLit (MachStr s))
598 dsLit (HsInteger i) = mkIntegerLit i
599 dsLit (HsInt i) = returnDs (mkConApp intDataCon [mkIntLit i])
600 dsLit (HsIntPrim i) = returnDs (mkIntLit i)
601 dsLit (HsFloatPrim f) = returnDs (mkLit (MachFloat f))
602 dsLit (HsDoublePrim d) = returnDs (mkLit (MachDouble d))
603 dsLit (HsLitLit str ty)
604 = ASSERT( maybeToBool maybe_ty )
605 returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
607 (maybe_ty, wrap_fn) = resultWrapper ty
608 Just rep_ty = maybe_ty
611 = mkIntegerLit (numerator r) `thenDs` \ num ->
612 mkIntegerLit (denominator r) `thenDs` \ denom ->
613 returnDs (mkConApp ratio_data_con [Type integer_ty, num, denom])
615 (ratio_data_con, integer_ty)
616 = case splitAlgTyConApp ty of
617 (tycon, [i_ty], [con])
618 -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)