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(..),
16 mkSimpleMatch, isDoExpr
18 import TcHsSyn ( TypecheckedHsExpr, TypecheckedHsBinds,
19 TypecheckedStmt, TypecheckedMatchContext
21 import TcType ( tcSplitAppTy, tcSplitFunTys, tcSplitTyConApp_maybe, tcTyConAppArgs,
22 isIntegerTy, tcSplitTyConApp, isUnLiftedType, Type )
24 import CoreUtils ( exprType, mkIfThenElse, bindNonRec )
27 import DsBinds ( dsMonoBinds, AutoScc(..) )
28 import DsGRHSs ( dsGuarded )
29 import DsCCall ( dsCCall, resultWrapper )
30 import DsListComp ( dsListComp )
31 import DsUtils ( mkErrorAppDs, mkDsLets, mkStringLit, mkStringLitFS,
32 mkConsExpr, mkNilExpr, mkIntegerLit
34 import Match ( matchWrapper, matchSimply )
36 import FieldLabel ( FieldLabel, fieldLabelTyCon )
37 import CostCentre ( mkUserCC )
38 import Id ( Id, idType, recordSelectorFieldLabel )
39 import PrelInfo ( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
40 import DataCon ( DataCon, dataConWrapId, dataConFieldLabels, dataConInstOrigArgTys )
41 import DataCon ( isExistentialDataCon )
42 import Literal ( Literal(..) )
43 import TyCon ( tyConDataCons )
44 import TysWiredIn ( tupleCon, listTyCon, charDataCon, intDataCon )
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 PatBindRhs 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 LambdaExpr [a_Match] `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)
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:_, _) = tcSplitFunTys (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:_, _) = tcSplitFunTys (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 CaseAlt matches `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 CaseAlt matches `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, tcSplitTyConApp_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 interpretation of ExprStmt depends on what sort of thing
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, _) = tcSplitFunTys (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 [])
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 = tcTyConAppArgs record_in_ty
400 out_inst_tys = tcTyConAppArgs record_out_ty
402 mk_val_arg field old_arg_id
403 = case [rhs | (sel_id, rhs, _) <- rbinds,
404 field == recordSelectorFieldLabel sel_id] of
405 (rhs:rest) -> ASSERT(null rest) rhs
406 [] -> HsVar old_arg_id
409 = newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
410 -- This call to dataConArgTys won't work for existentials
412 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
413 (dataConFieldLabels con) arg_ids
414 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConWrapId con))
419 returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
424 -- Record stuff doesn't work for existentials
425 ASSERT( all (not . isExistentialDataCon) data_cons )
427 -- It's important to generate the match with matchWrapper,
428 -- and the right hand sides with applications of the wrapper Id
429 -- so that everything works when we are doing fancy unboxing on the
430 -- constructor aguments.
431 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
432 matchWrapper RecUpd alts `thenDs` \ ([discrim_var], matching_code) ->
434 returnDs (bindNonRec discrim_var record_expr' matching_code)
437 updated_fields :: [FieldLabel]
438 updated_fields = [recordSelectorFieldLabel sel_id | (sel_id,_,_) <- rbinds]
440 -- Get the type constructor from the first field label,
441 -- so that we are sure it'll have all its DataCons
442 -- (In GHCI, it's possible that some TyCons may not have all
443 -- their constructors, in a module-loop situation.)
444 tycon = fieldLabelTyCon (head updated_fields)
445 data_cons = tyConDataCons tycon
446 cons_to_upd = filter has_all_fields data_cons
448 has_all_fields :: DataCon -> Bool
449 has_all_fields con_id
450 = all (`elem` con_fields) updated_fields
452 con_fields = dataConFieldLabels con_id
457 \underline{\bf Dictionary lambda and application}
458 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
459 @DictLam@ and @DictApp@ turn into the regular old things.
460 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
461 complicated; reminiscent of fully-applied constructors.
463 dsExpr (DictLam dictvars expr)
464 = dsExpr expr `thenDs` \ core_expr ->
465 returnDs (mkLams dictvars core_expr)
469 dsExpr (DictApp expr dicts) -- becomes a curried application
470 = dsExpr expr `thenDs` \ core_expr ->
471 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
477 -- HsSyn constructs that just shouldn't be here:
478 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
479 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
480 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
481 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
486 %--------------------------------------------------------------------
488 Basically does the translation given in the Haskell~1.3 report:
493 -> Id -- id for: return m
494 -> Id -- id for: (>>=) m
495 -> Id -- id for: fail m
496 -> Type -- Element type; the whole expression has type (m t)
499 dsDo do_or_lc stmts return_id then_id fail_id result_ty
501 (_, b_ty) = tcSplitAppTy result_ty -- result_ty must be of the form (m b)
502 is_do = case do_or_lc of
506 -- For ExprStmt, see the comments near HsExpr.HsStmt about
507 -- exactly what ExprStmts mean!
509 -- In dsDo we can only see DoStmt and ListComp (no gaurds)
511 go [ResultStmt expr locn]
512 | is_do = do_expr expr locn
513 | otherwise = do_expr expr locn `thenDs` \ expr2 ->
514 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
516 go (ExprStmt expr locn : stmts)
517 | is_do -- Do expression
518 = do_expr expr locn `thenDs` \ expr2 ->
519 go stmts `thenDs` \ rest ->
521 (_, a_ty) = tcSplitAppTy (exprType expr2) -- Must be of form (m a)
523 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
524 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
525 Lam ignored_result_id rest])
527 | otherwise -- List comprehension
528 = do_expr expr locn `thenDs` \ expr2 ->
529 go stmts `thenDs` \ rest ->
531 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
533 mkStringLit msg `thenDs` \ core_msg ->
534 returnDs (mkIfThenElse expr2 rest
535 (App (App (Var fail_id) (Type b_ty)) core_msg))
537 go (LetStmt binds : stmts )
538 = go stmts `thenDs` \ rest ->
541 go (BindStmt pat expr locn : stmts)
543 dsExpr expr `thenDs` \ expr2 ->
545 (_, a_ty) = tcSplitAppTy (exprType expr2) -- Must be of form (m a)
546 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
547 (HsLit (HsString (_PK_ msg)))
548 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
549 main_match = mkSimpleMatch [pat]
550 (HsDoOut do_or_lc stmts return_id then_id
551 fail_id result_ty locn)
552 (Just result_ty) locn
554 | failureFreePat pat = [main_match]
557 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
560 matchWrapper (DoCtxt do_or_lc) the_matches `thenDs` \ (binders, matching_code) ->
561 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
562 mkLams binders matching_code])
567 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
571 %************************************************************************
573 \subsection[DsExpr-literals]{Literals}
575 %************************************************************************
577 We give int/float literals type @Integer@ and @Rational@, respectively.
578 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
581 ToDo: put in range checks for when converting ``@i@''
582 (or should that be in the typechecker?)
584 For numeric literals, we try to detect there use at a standard type
585 (@Int@, @Float@, etc.) are directly put in the right constructor.
586 [NB: down with the @App@ conversion.]
588 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
591 dsLit :: HsLit -> DsM CoreExpr
592 dsLit (HsChar c) = returnDs (mkConApp charDataCon [mkLit (MachChar c)])
593 dsLit (HsCharPrim c) = returnDs (mkLit (MachChar c))
594 dsLit (HsString str) = mkStringLitFS str
595 dsLit (HsStringPrim s) = returnDs (mkLit (MachStr s))
596 dsLit (HsInteger i) = mkIntegerLit i
597 dsLit (HsInt i) = returnDs (mkConApp intDataCon [mkIntLit i])
598 dsLit (HsIntPrim i) = returnDs (mkIntLit i)
599 dsLit (HsFloatPrim f) = returnDs (mkLit (MachFloat f))
600 dsLit (HsDoublePrim d) = returnDs (mkLit (MachDouble d))
601 dsLit (HsLitLit str ty)
602 = ASSERT( maybeToBool maybe_ty )
603 returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
605 (maybe_ty, wrap_fn) = resultWrapper ty
606 Just rep_ty = maybe_ty
609 = mkIntegerLit (numerator r) `thenDs` \ num ->
610 mkIntegerLit (denominator r) `thenDs` \ denom ->
611 returnDs (mkConApp ratio_data_con [Type integer_ty, num, denom])
613 (ratio_data_con, integer_ty)
614 = case tcSplitTyConApp ty of
615 (tycon, [i_ty]) -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)
616 (head (tyConDataCons tycon), i_ty)