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(..), HsMatchContext(..), HsDoContext(..),
15 Match(..), HsBinds(..), MonoBinds(..),
18 import TcHsSyn ( TypecheckedHsExpr, TypecheckedHsBinds, TypecheckedStmt )
19 import TcType ( tcSplitAppTy, tcSplitFunTys, tcSplitTyConApp_maybe, tcTyConAppArgs,
20 isIntegerTy, tcSplitTyConApp, isUnLiftedType, Type )
22 import CoreUtils ( exprType, mkIfThenElse, bindNonRec )
25 import DsBinds ( dsMonoBinds, AutoScc(..) )
26 import DsGRHSs ( dsGuarded )
27 import DsCCall ( dsCCall, resultWrapper )
28 import DsListComp ( dsListComp )
29 import DsUtils ( mkErrorAppDs, mkDsLets, mkStringLit, mkStringLitFS,
30 mkConsExpr, mkNilExpr, mkIntegerLit
32 import Match ( matchWrapper, matchSimply )
34 import FieldLabel ( FieldLabel, fieldLabelTyCon )
35 import CostCentre ( mkUserCC )
36 import Id ( Id, idType, recordSelectorFieldLabel )
37 import PrelInfo ( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
38 import DataCon ( DataCon, dataConWrapId, dataConFieldLabels, dataConInstOrigArgTys )
39 import DataCon ( isExistentialDataCon )
40 import Literal ( Literal(..) )
41 import TyCon ( tyConDataCons )
42 import TysWiredIn ( tupleCon, listTyCon, charDataCon, intDataCon )
43 import BasicTypes ( RecFlag(..), Boxity(..) )
44 import Maybes ( maybeToBool )
45 import PrelNames ( hasKey, ratioTyConKey )
46 import Util ( zipEqual, zipWithEqual )
49 import Ratio ( numerator, denominator )
53 %************************************************************************
57 %************************************************************************
59 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
60 and transforming it into one for the let-bindings enclosing the body.
62 This may seem a bit odd, but (source) let bindings can contain unboxed
67 This must be transformed to a case expression and, if the type has
68 more than one constructor, may fail.
71 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
76 dsLet (ThenBinds b1 b2) body
77 = dsLet b2 body `thenDs` \ body' ->
80 -- Special case for bindings which bind unlifted variables
81 -- Silently ignore INLINE pragmas...
82 dsLet (MonoBind (AbsBinds [] [] binder_triples inlines
83 (PatMonoBind pat grhss loc)) sigs is_rec) body
84 | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
85 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
87 dsGuarded grhss `thenDs` \ rhs ->
89 body' = foldr bind body binder_triples
90 bind (tyvars, g, l) body = ASSERT( null tyvars )
91 bindNonRec g (Var l) body
93 mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat))
94 `thenDs` \ error_expr ->
95 matchSimply rhs PatBindRhs pat body' error_expr
97 result_ty = exprType body
99 -- Ordinary case for bindings
100 dsLet (MonoBind binds sigs is_rec) body
101 = dsMonoBinds NoSccs binds [] `thenDs` \ prs ->
103 Recursive -> returnDs (Let (Rec prs) body)
104 NonRecursive -> returnDs (mkDsLets [NonRec b r | (b,r) <- prs] body)
107 %************************************************************************
109 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
111 %************************************************************************
114 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
116 dsExpr (HsVar var) = returnDs (Var var)
117 dsExpr (HsIPVar var) = returnDs (Var var)
118 dsExpr (HsLit lit) = dsLit lit
119 -- HsOverLit has been gotten rid of by the type checker
121 dsExpr expr@(HsLam a_Match)
122 = matchWrapper LambdaExpr [a_Match] `thenDs` \ (binders, matching_code) ->
123 returnDs (mkLams binders matching_code)
125 dsExpr expr@(HsApp fun arg)
126 = dsExpr fun `thenDs` \ core_fun ->
127 dsExpr arg `thenDs` \ core_arg ->
128 returnDs (core_fun `App` core_arg)
131 Operator sections. At first it looks as if we can convert
140 But no! expr might be a redex, and we can lose laziness badly this
145 for example. So we convert instead to
147 let y = expr in \x -> op y x
149 If \tr{expr} is actually just a variable, say, then the simplifier
153 dsExpr (OpApp e1 op _ e2)
154 = dsExpr op `thenDs` \ core_op ->
155 -- for the type of y, we need the type of op's 2nd argument
156 dsExpr e1 `thenDs` \ x_core ->
157 dsExpr e2 `thenDs` \ y_core ->
158 returnDs (mkApps core_op [x_core, y_core])
160 dsExpr (SectionL expr op)
161 = dsExpr op `thenDs` \ core_op ->
162 -- for the type of y, we need the type of op's 2nd argument
164 (x_ty:y_ty:_, _) = tcSplitFunTys (exprType core_op)
166 dsExpr expr `thenDs` \ x_core ->
167 newSysLocalDs x_ty `thenDs` \ x_id ->
168 newSysLocalDs y_ty `thenDs` \ y_id ->
170 returnDs (bindNonRec x_id x_core $
171 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
173 -- dsExpr (SectionR op expr) -- \ x -> op x expr
174 dsExpr (SectionR op expr)
175 = dsExpr op `thenDs` \ core_op ->
176 -- for the type of x, we need the type of op's 2nd argument
178 (x_ty:y_ty:_, _) = tcSplitFunTys (exprType core_op)
180 dsExpr expr `thenDs` \ y_core ->
181 newSysLocalDs x_ty `thenDs` \ x_id ->
182 newSysLocalDs y_ty `thenDs` \ y_id ->
184 returnDs (bindNonRec y_id y_core $
185 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
187 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
188 = mapDs dsExpr args `thenDs` \ core_args ->
189 dsCCall lbl core_args may_gc is_asm result_ty
190 -- dsCCall does all the unboxification, etc.
192 dsExpr (HsSCC cc expr)
193 = dsExpr expr `thenDs` \ core_expr ->
194 getModuleDs `thenDs` \ mod_name ->
195 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
197 -- special case to handle unboxed tuple patterns.
199 dsExpr (HsCase discrim matches src_loc)
200 | all ubx_tuple_match matches
201 = putSrcLocDs src_loc $
202 dsExpr discrim `thenDs` \ core_discrim ->
203 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
204 case matching_code of
205 Case (Var x) bndr alts | x == discrim_var ->
206 returnDs (Case core_discrim bndr alts)
207 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
209 ubx_tuple_match (Match _ [TuplePat ps Unboxed] _ _) = True
210 ubx_tuple_match _ = False
212 dsExpr (HsCase discrim matches src_loc)
213 = putSrcLocDs src_loc $
214 dsExpr discrim `thenDs` \ core_discrim ->
215 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
216 returnDs (bindNonRec discrim_var core_discrim matching_code)
218 dsExpr (HsLet binds body)
219 = dsExpr body `thenDs` \ body' ->
222 dsExpr (HsWith expr binds)
223 = dsExpr expr `thenDs` \ expr' ->
224 foldlDs dsIPBind expr' binds
227 = dsExpr e `thenDs` \ e' ->
228 returnDs (Let (NonRec n e') body)
230 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
231 | maybeToBool maybe_list_comp
232 = -- Special case for list comprehensions
233 putSrcLocDs src_loc $
234 dsListComp stmts elt_ty
237 = putSrcLocDs src_loc $
238 dsDo do_or_lc stmts return_id then_id fail_id result_ty
241 = case (do_or_lc, tcSplitTyConApp_maybe result_ty) of
242 (ListComp, Just (tycon, [elt_ty]))
246 -- We need the ListComp form to use deListComp (rather than the "do" form)
247 -- because the interpretation of ExprStmt depends on what sort of thing
250 Just elt_ty = maybe_list_comp
252 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
253 = putSrcLocDs src_loc $
254 dsExpr guard_expr `thenDs` \ core_guard ->
255 dsExpr then_expr `thenDs` \ core_then ->
256 dsExpr else_expr `thenDs` \ core_else ->
257 returnDs (mkIfThenElse core_guard core_then core_else)
262 \underline{\bf Type lambda and application}
263 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
265 dsExpr (TyLam tyvars expr)
266 = dsExpr expr `thenDs` \ core_expr ->
267 returnDs (mkLams tyvars core_expr)
269 dsExpr (TyApp expr tys)
270 = dsExpr expr `thenDs` \ core_expr ->
271 returnDs (mkTyApps core_expr tys)
276 \underline{\bf Various data construction things}
277 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
279 dsExpr (ExplicitListOut ty xs)
282 go [] = returnDs (mkNilExpr ty)
283 go (x:xs) = dsExpr x `thenDs` \ core_x ->
284 go xs `thenDs` \ core_xs ->
285 returnDs (mkConsExpr ty core_x core_xs)
287 dsExpr (ExplicitTuple expr_list boxity)
288 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
289 returnDs (mkConApp (tupleCon boxity (length expr_list))
290 (map (Type . exprType) core_exprs ++ core_exprs))
292 dsExpr (ArithSeqOut expr (From from))
293 = dsExpr expr `thenDs` \ expr2 ->
294 dsExpr from `thenDs` \ from2 ->
295 returnDs (App expr2 from2)
297 dsExpr (ArithSeqOut expr (FromTo from two))
298 = dsExpr expr `thenDs` \ expr2 ->
299 dsExpr from `thenDs` \ from2 ->
300 dsExpr two `thenDs` \ two2 ->
301 returnDs (mkApps expr2 [from2, two2])
303 dsExpr (ArithSeqOut expr (FromThen from thn))
304 = dsExpr expr `thenDs` \ expr2 ->
305 dsExpr from `thenDs` \ from2 ->
306 dsExpr thn `thenDs` \ thn2 ->
307 returnDs (mkApps expr2 [from2, thn2])
309 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
310 = dsExpr expr `thenDs` \ expr2 ->
311 dsExpr from `thenDs` \ from2 ->
312 dsExpr thn `thenDs` \ thn2 ->
313 dsExpr two `thenDs` \ two2 ->
314 returnDs (mkApps expr2 [from2, thn2, two2])
318 \underline{\bf Record construction and update}
319 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
320 For record construction we do this (assuming T has three arguments)
324 let err = /\a -> recConErr a
325 T (recConErr t1 "M.lhs/230/op1")
327 (recConErr t1 "M.lhs/230/op3")
329 @recConErr@ then converts its arugment string into a proper message
330 before printing it as
332 M.lhs, line 230: missing field op1 was evaluated
335 We also handle @C{}@ as valid construction syntax for an unlabelled
336 constructor @C@, setting all of @C@'s fields to bottom.
339 dsExpr (RecordConOut data_con con_expr rbinds)
340 = dsExpr con_expr `thenDs` \ con_expr' ->
342 (arg_tys, _) = tcSplitFunTys (exprType con_expr')
345 = case [rhs | (sel_id,rhs,_) <- rbinds,
346 lbl == recordSelectorFieldLabel sel_id] of
347 (rhs:rhss) -> ASSERT( null rhss )
349 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
350 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
352 labels = dataConFieldLabels data_con
356 then mapDs unlabelled_bottom arg_tys
357 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
358 `thenDs` \ con_args ->
360 returnDs (mkApps con_expr' con_args)
363 Record update is a little harder. Suppose we have the decl:
365 data T = T1 {op1, op2, op3 :: Int}
366 | T2 {op4, op2 :: Int}
369 Then we translate as follows:
375 T1 op1 _ op3 -> T1 op1 op2 op3
376 T2 op4 _ -> T2 op4 op2
377 other -> recUpdError "M.lhs/230"
379 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
380 RHSs, and do not generate a Core constructor application directly, because the constructor
381 might do some argument-evaluation first; and may have to throw away some
385 dsExpr (RecordUpdOut record_expr record_out_ty dicts [])
388 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
389 = getSrcLocDs `thenDs` \ src_loc ->
390 dsExpr record_expr `thenDs` \ record_expr' ->
392 -- Desugar the rbinds, and generate let-bindings if
393 -- necessary so that we don't lose sharing
396 record_in_ty = exprType record_expr'
397 in_inst_tys = tcTyConAppArgs record_in_ty
398 out_inst_tys = tcTyConAppArgs record_out_ty
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 (dataConInstOrigArgTys 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) data_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 RecUpd alts `thenDs` \ ([discrim_var], matching_code) ->
432 returnDs (bindNonRec discrim_var record_expr' matching_code)
435 updated_fields :: [FieldLabel]
436 updated_fields = [recordSelectorFieldLabel sel_id | (sel_id,_,_) <- rbinds]
438 -- Get the type constructor from the first field label,
439 -- so that we are sure it'll have all its DataCons
440 -- (In GHCI, it's possible that some TyCons may not have all
441 -- their constructors, in a module-loop situation.)
442 tycon = fieldLabelTyCon (head updated_fields)
443 data_cons = tyConDataCons tycon
444 cons_to_upd = filter has_all_fields data_cons
446 has_all_fields :: DataCon -> Bool
447 has_all_fields con_id
448 = all (`elem` con_fields) updated_fields
450 con_fields = dataConFieldLabels con_id
455 \underline{\bf Dictionary lambda and application}
456 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
457 @DictLam@ and @DictApp@ turn into the regular old things.
458 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
459 complicated; reminiscent of fully-applied constructors.
461 dsExpr (DictLam dictvars expr)
462 = dsExpr expr `thenDs` \ core_expr ->
463 returnDs (mkLams dictvars core_expr)
467 dsExpr (DictApp expr dicts) -- becomes a curried application
468 = dsExpr expr `thenDs` \ core_expr ->
469 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
475 -- HsSyn constructs that just shouldn't be here:
476 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
477 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
478 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
479 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
484 %--------------------------------------------------------------------
486 Basically does the translation given in the Haskell~1.3 report:
491 -> Id -- id for: return m
492 -> Id -- id for: (>>=) m
493 -> Id -- id for: fail m
494 -> Type -- Element type; the whole expression has type (m t)
497 dsDo do_or_lc stmts return_id then_id fail_id result_ty
499 (_, b_ty) = tcSplitAppTy result_ty -- result_ty must be of the form (m b)
500 is_do = case do_or_lc of
504 -- For ExprStmt, see the comments near HsExpr.HsStmt about
505 -- exactly what ExprStmts mean!
507 -- In dsDo we can only see DoStmt and ListComp (no gaurds)
509 go [ResultStmt expr locn]
510 | is_do = do_expr expr locn
511 | otherwise = do_expr expr locn `thenDs` \ expr2 ->
512 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
514 go (ExprStmt expr locn : stmts)
515 | is_do -- Do expression
516 = do_expr expr locn `thenDs` \ expr2 ->
517 go stmts `thenDs` \ rest ->
519 (_, a_ty) = tcSplitAppTy (exprType expr2) -- Must be of form (m a)
521 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
522 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
523 Lam ignored_result_id rest])
525 | otherwise -- List comprehension
526 = do_expr expr locn `thenDs` \ expr2 ->
527 go stmts `thenDs` \ rest ->
529 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
531 mkStringLit msg `thenDs` \ core_msg ->
532 returnDs (mkIfThenElse expr2 rest
533 (App (App (Var fail_id) (Type b_ty)) core_msg))
535 go (LetStmt binds : stmts )
536 = go stmts `thenDs` \ rest ->
539 go (BindStmt pat expr locn : stmts)
541 dsExpr expr `thenDs` \ expr2 ->
543 (_, a_ty) = tcSplitAppTy (exprType expr2) -- Must be of form (m a)
544 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
545 (HsLit (HsString (_PK_ msg)))
546 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
547 main_match = mkSimpleMatch [pat]
548 (HsDoOut do_or_lc stmts return_id then_id
549 fail_id result_ty locn)
550 (Just result_ty) locn
552 | failureFreePat pat = [main_match]
555 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
558 matchWrapper (DoCtxt do_or_lc) the_matches `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)
569 %************************************************************************
571 \subsection[DsExpr-literals]{Literals}
573 %************************************************************************
575 We give int/float literals type @Integer@ and @Rational@, respectively.
576 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
579 ToDo: put in range checks for when converting ``@i@''
580 (or should that be in the typechecker?)
582 For numeric literals, we try to detect there use at a standard type
583 (@Int@, @Float@, etc.) are directly put in the right constructor.
584 [NB: down with the @App@ conversion.]
586 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
589 dsLit :: HsLit -> DsM CoreExpr
590 dsLit (HsChar c) = returnDs (mkConApp charDataCon [mkLit (MachChar c)])
591 dsLit (HsCharPrim c) = returnDs (mkLit (MachChar c))
592 dsLit (HsString str) = mkStringLitFS str
593 dsLit (HsStringPrim s) = returnDs (mkLit (MachStr s))
594 dsLit (HsInteger i) = mkIntegerLit i
595 dsLit (HsInt i) = returnDs (mkConApp intDataCon [mkIntLit i])
596 dsLit (HsIntPrim i) = returnDs (mkIntLit i)
597 dsLit (HsFloatPrim f) = returnDs (mkLit (MachFloat f))
598 dsLit (HsDoublePrim d) = returnDs (mkLit (MachDouble d))
599 dsLit (HsLitLit str ty)
600 = ASSERT( maybeToBool maybe_ty )
601 returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
603 (maybe_ty, wrap_fn) = resultWrapper ty
604 Just rep_ty = maybe_ty
607 = mkIntegerLit (numerator r) `thenDs` \ num ->
608 mkIntegerLit (denominator r) `thenDs` \ denom ->
609 returnDs (mkConApp ratio_data_con [Type integer_ty, num, denom])
611 (ratio_data_con, integer_ty)
612 = case tcSplitTyConApp ty of
613 (tycon, [i_ty]) -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)
614 (head (tyConDataCons tycon), i_ty)