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, outPatType )
20 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
21 -- needs to see source types (newtypes etc), and sometimes not
22 -- So WATCH OUT; check each use of split*Ty functions.
23 -- Sigh. This is a pain.
25 import TcType ( tcSplitAppTy, tcSplitFunTys, tcSplitTyConApp_maybe, tcTyConAppArgs,
26 isIntegerTy, tcSplitTyConApp, isUnLiftedType, Type )
27 import Type ( splitFunTys )
29 import CoreUtils ( exprType, mkIfThenElse, bindNonRec )
32 import DsBinds ( dsMonoBinds, AutoScc(..) )
33 import DsGRHSs ( dsGuarded )
34 import DsCCall ( dsCCall, resultWrapper )
35 import DsListComp ( dsListComp )
36 import DsUtils ( mkErrorAppDs, mkStringLit, mkStringLitFS,
37 mkConsExpr, mkNilExpr, mkIntegerLit
39 import Match ( matchWrapper, matchSimply )
41 import FieldLabel ( FieldLabel, fieldLabelTyCon )
42 import CostCentre ( mkUserCC )
43 import Id ( Id, idType, recordSelectorFieldLabel )
44 import PrelInfo ( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
45 import DataCon ( DataCon, dataConWrapId, dataConFieldLabels, dataConInstOrigArgTys )
46 import DataCon ( isExistentialDataCon )
47 import Literal ( Literal(..) )
48 import TyCon ( tyConDataCons )
49 import TysWiredIn ( tupleCon, listTyCon, charDataCon, intDataCon )
50 import BasicTypes ( RecFlag(..), Boxity(..), ipNameName )
51 import Maybes ( maybeToBool )
52 import PrelNames ( hasKey, ratioTyConKey )
53 import Util ( zipEqual, zipWithEqual )
56 import Ratio ( numerator, denominator )
60 %************************************************************************
64 %************************************************************************
66 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
67 and transforming it into one for the let-bindings enclosing the body.
69 This may seem a bit odd, but (source) let bindings can contain unboxed
74 This must be transformed to a case expression and, if the type has
75 more than one constructor, may fail.
78 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
83 dsLet (ThenBinds b1 b2) body
84 = dsLet b2 body `thenDs` \ body' ->
87 -- Special case for bindings which bind unlifted variables
88 -- We need to do a case right away, rather than building
89 -- a tuple and doing selections.
90 -- Silently ignore INLINE pragmas...
91 dsLet bind@(MonoBind (AbsBinds [] [] exports inlines binds) sigs is_rec) body
92 | or [isUnLiftedType (idType g) | (_, g, l) <- exports]
93 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
94 -- Unlifted bindings are always non-recursive
95 -- and are always a Fun or Pat monobind
97 -- ToDo: in some bizarre case it's conceivable that there
98 -- could be dict binds in the 'binds'. (See the notes
99 -- below. Then pattern-match would fail. Urk.)
101 FunMonoBind fun _ matches loc
103 matchWrapper (FunRhs fun) matches `thenDs` \ (args, rhs) ->
104 ASSERT( null args ) -- Functions aren't lifted
105 returnDs (bindNonRec fun rhs body_w_exports)
107 PatMonoBind pat grhss loc
109 dsGuarded grhss `thenDs` \ rhs ->
110 mk_error_app pat `thenDs` \ error_expr ->
111 matchSimply rhs PatBindRhs pat body_w_exports error_expr
113 other -> pprPanic "dsLet: unlifted" (ppr bind $$ ppr body)
115 body_w_exports = foldr bind_export body exports
116 bind_export (tvs, g, l) body = ASSERT( null tvs )
117 bindNonRec g (Var l) body
119 mk_error_app pat = mkErrorAppDs iRREFUT_PAT_ERROR_ID
123 -- Ordinary case for bindings
124 dsLet (MonoBind binds sigs is_rec) body
125 = dsMonoBinds NoSccs binds [] `thenDs` \ prs ->
126 returnDs (Let (Rec prs) body)
127 -- Use a Rec regardless of is_rec.
128 -- Why? Because it allows the MonoBinds to be all
129 -- mixed up, which is what happens in one rare case
130 -- Namely, for an AbsBind with no tyvars and no dicts,
131 -- but which does have dictionary bindings.
132 -- See notes with TcSimplify.inferLoop [NO TYVARS]
133 -- It turned out that wrapping a Rec here was the easiest solution
135 -- NB The previous case dealt with unlifted bindings, so we
136 -- only have to deal with lifted ones now; so Rec is ok
139 %************************************************************************
141 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
143 %************************************************************************
146 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
148 dsExpr (HsVar var) = returnDs (Var var)
149 dsExpr (HsIPVar ip) = returnDs (Var (ipNameName ip))
150 dsExpr (HsLit lit) = dsLit lit
151 -- HsOverLit has been gotten rid of by the type checker
153 dsExpr expr@(HsLam a_Match)
154 = matchWrapper LambdaExpr [a_Match] `thenDs` \ (binders, matching_code) ->
155 returnDs (mkLams binders matching_code)
157 dsExpr expr@(HsApp fun arg)
158 = dsExpr fun `thenDs` \ core_fun ->
159 dsExpr arg `thenDs` \ core_arg ->
160 returnDs (core_fun `App` core_arg)
163 Operator sections. At first it looks as if we can convert
172 But no! expr might be a redex, and we can lose laziness badly this
177 for example. So we convert instead to
179 let y = expr in \x -> op y x
181 If \tr{expr} is actually just a variable, say, then the simplifier
185 dsExpr (OpApp e1 op _ e2)
186 = dsExpr op `thenDs` \ core_op ->
187 -- for the type of y, we need the type of op's 2nd argument
188 dsExpr e1 `thenDs` \ x_core ->
189 dsExpr e2 `thenDs` \ y_core ->
190 returnDs (mkApps core_op [x_core, y_core])
192 dsExpr (SectionL expr op)
193 = dsExpr op `thenDs` \ core_op ->
194 -- for the type of y, we need the type of op's 2nd argument
196 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
197 -- Must look through an implicit-parameter type;
198 -- newtype impossible; hence Type.splitFunTys
200 dsExpr expr `thenDs` \ x_core ->
201 newSysLocalDs x_ty `thenDs` \ x_id ->
202 newSysLocalDs y_ty `thenDs` \ y_id ->
204 returnDs (bindNonRec x_id x_core $
205 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
207 -- dsExpr (SectionR op expr) -- \ x -> op x expr
208 dsExpr (SectionR op expr)
209 = dsExpr op `thenDs` \ core_op ->
210 -- for the type of x, we need the type of op's 2nd argument
212 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
213 -- See comment with SectionL
215 dsExpr expr `thenDs` \ y_core ->
216 newSysLocalDs x_ty `thenDs` \ x_id ->
217 newSysLocalDs y_ty `thenDs` \ y_id ->
219 returnDs (bindNonRec y_id y_core $
220 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
222 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
223 = mapDs dsExpr args `thenDs` \ core_args ->
224 dsCCall lbl core_args may_gc is_asm result_ty
225 -- dsCCall does all the unboxification, etc.
227 dsExpr (HsSCC cc expr)
228 = dsExpr expr `thenDs` \ core_expr ->
229 getModuleDs `thenDs` \ mod_name ->
230 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
232 -- special case to handle unboxed tuple patterns.
234 dsExpr (HsCase discrim matches src_loc)
235 | all ubx_tuple_match matches
236 = putSrcLocDs src_loc $
237 dsExpr discrim `thenDs` \ core_discrim ->
238 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
239 case matching_code of
240 Case (Var x) bndr alts | x == discrim_var ->
241 returnDs (Case core_discrim bndr alts)
242 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
244 ubx_tuple_match (Match [TuplePat ps Unboxed] _ _) = True
245 ubx_tuple_match _ = False
247 dsExpr (HsCase discrim matches src_loc)
248 = putSrcLocDs src_loc $
249 dsExpr discrim `thenDs` \ core_discrim ->
250 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
251 returnDs (bindNonRec discrim_var core_discrim matching_code)
253 dsExpr (HsLet binds body)
254 = dsExpr body `thenDs` \ body' ->
257 dsExpr (HsWith expr binds)
258 = dsExpr expr `thenDs` \ expr' ->
259 foldlDs dsIPBind expr' binds
262 = dsExpr e `thenDs` \ e' ->
263 returnDs (Let (NonRec (ipNameName n) e') body)
265 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
266 | maybeToBool maybe_list_comp
267 = -- Special case for list comprehensions
268 putSrcLocDs src_loc $
269 dsListComp stmts elt_ty
272 = putSrcLocDs src_loc $
273 dsDo do_or_lc stmts return_id then_id fail_id result_ty
276 = case (do_or_lc, tcSplitTyConApp_maybe result_ty) of
277 (ListComp, Just (tycon, [elt_ty]))
281 -- We need the ListComp form to use deListComp (rather than the "do" form)
282 -- because the interpretation of ExprStmt depends on what sort of thing
285 Just elt_ty = maybe_list_comp
287 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
288 = putSrcLocDs src_loc $
289 dsExpr guard_expr `thenDs` \ core_guard ->
290 dsExpr then_expr `thenDs` \ core_then ->
291 dsExpr else_expr `thenDs` \ core_else ->
292 returnDs (mkIfThenElse core_guard core_then core_else)
297 \underline{\bf Type lambda and application}
298 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
300 dsExpr (TyLam tyvars expr)
301 = dsExpr expr `thenDs` \ core_expr ->
302 returnDs (mkLams tyvars core_expr)
304 dsExpr (TyApp expr tys)
305 = dsExpr expr `thenDs` \ core_expr ->
306 returnDs (mkTyApps core_expr tys)
311 \underline{\bf Various data construction things}
312 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
314 dsExpr (ExplicitList ty xs)
317 go [] = returnDs (mkNilExpr ty)
318 go (x:xs) = dsExpr x `thenDs` \ core_x ->
319 go xs `thenDs` \ core_xs ->
320 returnDs (mkConsExpr ty core_x core_xs)
322 dsExpr (ExplicitTuple expr_list boxity)
323 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
324 returnDs (mkConApp (tupleCon boxity (length expr_list))
325 (map (Type . exprType) core_exprs ++ core_exprs))
327 dsExpr (ArithSeqOut expr (From from))
328 = dsExpr expr `thenDs` \ expr2 ->
329 dsExpr from `thenDs` \ from2 ->
330 returnDs (App expr2 from2)
332 dsExpr (ArithSeqOut expr (FromTo from two))
333 = dsExpr expr `thenDs` \ expr2 ->
334 dsExpr from `thenDs` \ from2 ->
335 dsExpr two `thenDs` \ two2 ->
336 returnDs (mkApps expr2 [from2, two2])
338 dsExpr (ArithSeqOut expr (FromThen from thn))
339 = dsExpr expr `thenDs` \ expr2 ->
340 dsExpr from `thenDs` \ from2 ->
341 dsExpr thn `thenDs` \ thn2 ->
342 returnDs (mkApps expr2 [from2, thn2])
344 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
345 = dsExpr expr `thenDs` \ expr2 ->
346 dsExpr from `thenDs` \ from2 ->
347 dsExpr thn `thenDs` \ thn2 ->
348 dsExpr two `thenDs` \ two2 ->
349 returnDs (mkApps expr2 [from2, thn2, two2])
353 \underline{\bf Record construction and update}
354 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
355 For record construction we do this (assuming T has three arguments)
359 let err = /\a -> recConErr a
360 T (recConErr t1 "M.lhs/230/op1")
362 (recConErr t1 "M.lhs/230/op3")
364 @recConErr@ then converts its arugment string into a proper message
365 before printing it as
367 M.lhs, line 230: missing field op1 was evaluated
370 We also handle @C{}@ as valid construction syntax for an unlabelled
371 constructor @C@, setting all of @C@'s fields to bottom.
374 dsExpr (RecordConOut data_con con_expr rbinds)
375 = dsExpr con_expr `thenDs` \ con_expr' ->
377 (arg_tys, _) = tcSplitFunTys (exprType con_expr')
378 -- A newtype in the corner should be opaque;
379 -- hence TcType.tcSplitFunTys
382 = case [rhs | (sel_id,rhs,_) <- rbinds,
383 lbl == recordSelectorFieldLabel sel_id] of
384 (rhs:rhss) -> ASSERT( null rhss )
386 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
387 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
389 labels = dataConFieldLabels data_con
393 then mapDs unlabelled_bottom arg_tys
394 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
395 `thenDs` \ con_args ->
397 returnDs (mkApps con_expr' con_args)
400 Record update is a little harder. Suppose we have the decl:
402 data T = T1 {op1, op2, op3 :: Int}
403 | T2 {op4, op2 :: Int}
406 Then we translate as follows:
412 T1 op1 _ op3 -> T1 op1 op2 op3
413 T2 op4 _ -> T2 op4 op2
414 other -> recUpdError "M.lhs/230"
416 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
417 RHSs, and do not generate a Core constructor application directly, because the constructor
418 might do some argument-evaluation first; and may have to throw away some
422 dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty dicts [])
425 dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty dicts rbinds)
426 = getSrcLocDs `thenDs` \ src_loc ->
427 dsExpr record_expr `thenDs` \ record_expr' ->
429 -- Desugar the rbinds, and generate let-bindings if
430 -- necessary so that we don't lose sharing
433 in_inst_tys = tcTyConAppArgs record_in_ty -- Newtype opaque
434 out_inst_tys = tcTyConAppArgs record_out_ty -- Newtype opaque
436 mk_val_arg field old_arg_id
437 = case [rhs | (sel_id, rhs, _) <- rbinds,
438 field == recordSelectorFieldLabel sel_id] of
439 (rhs:rest) -> ASSERT(null rest) rhs
440 [] -> HsVar old_arg_id
443 = newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
444 -- This call to dataConArgTys won't work for existentials
446 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
447 (dataConFieldLabels con) arg_ids
448 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConWrapId con))
453 returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
458 -- Record stuff doesn't work for existentials
459 ASSERT( all (not . isExistentialDataCon) data_cons )
461 -- It's important to generate the match with matchWrapper,
462 -- and the right hand sides with applications of the wrapper Id
463 -- so that everything works when we are doing fancy unboxing on the
464 -- constructor aguments.
465 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
466 matchWrapper RecUpd alts `thenDs` \ ([discrim_var], matching_code) ->
468 returnDs (bindNonRec discrim_var record_expr' matching_code)
471 updated_fields :: [FieldLabel]
472 updated_fields = [recordSelectorFieldLabel sel_id | (sel_id,_,_) <- rbinds]
474 -- Get the type constructor from the first field label,
475 -- so that we are sure it'll have all its DataCons
476 -- (In GHCI, it's possible that some TyCons may not have all
477 -- their constructors, in a module-loop situation.)
478 tycon = fieldLabelTyCon (head updated_fields)
479 data_cons = tyConDataCons tycon
480 cons_to_upd = filter has_all_fields data_cons
482 has_all_fields :: DataCon -> Bool
483 has_all_fields con_id
484 = all (`elem` con_fields) updated_fields
486 con_fields = dataConFieldLabels con_id
491 \underline{\bf Dictionary lambda and application}
492 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
493 @DictLam@ and @DictApp@ turn into the regular old things.
494 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
495 complicated; reminiscent of fully-applied constructors.
497 dsExpr (DictLam dictvars expr)
498 = dsExpr expr `thenDs` \ core_expr ->
499 returnDs (mkLams dictvars core_expr)
503 dsExpr (DictApp expr dicts) -- becomes a curried application
504 = dsExpr expr `thenDs` \ core_expr ->
505 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
511 -- HsSyn constructs that just shouldn't be here:
512 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
513 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
514 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
519 %--------------------------------------------------------------------
521 Basically does the translation given in the Haskell~1.3 report:
526 -> Id -- id for: return m
527 -> Id -- id for: (>>=) m
528 -> Id -- id for: fail m
529 -> Type -- Element type; the whole expression has type (m t)
532 dsDo do_or_lc stmts return_id then_id fail_id result_ty
534 (_, b_ty) = tcSplitAppTy result_ty -- result_ty must be of the form (m b)
535 is_do = case do_or_lc of
539 -- For ExprStmt, see the comments near HsExpr.Stmt about
540 -- exactly what ExprStmts mean!
542 -- In dsDo we can only see DoStmt and ListComp (no gaurds)
544 go [ResultStmt expr locn]
545 | is_do = do_expr expr locn
546 | otherwise = do_expr expr locn `thenDs` \ expr2 ->
547 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
549 go (ExprStmt expr a_ty locn : stmts)
550 | is_do -- Do expression
551 = do_expr expr locn `thenDs` \ expr2 ->
552 go stmts `thenDs` \ rest ->
553 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
554 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
555 Lam ignored_result_id rest])
557 | otherwise -- List comprehension
558 = do_expr expr locn `thenDs` \ expr2 ->
559 go stmts `thenDs` \ rest ->
561 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
563 mkStringLit msg `thenDs` \ core_msg ->
564 returnDs (mkIfThenElse expr2 rest
565 (App (App (Var fail_id) (Type b_ty)) core_msg))
567 go (LetStmt binds : stmts )
568 = go stmts `thenDs` \ rest ->
571 go (BindStmt pat expr locn : stmts)
573 dsExpr expr `thenDs` \ expr2 ->
575 a_ty = outPatType pat
576 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
577 (HsLit (HsString (_PK_ msg)))
578 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
579 main_match = mkSimpleMatch [pat]
580 (HsDoOut do_or_lc stmts return_id then_id
581 fail_id result_ty locn)
584 | failureFreePat pat = [main_match]
587 , mkSimpleMatch [WildPat a_ty] fail_expr result_ty locn
590 matchWrapper (DoCtxt do_or_lc) the_matches `thenDs` \ (binders, matching_code) ->
591 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
592 mkLams binders matching_code])
597 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
601 %************************************************************************
603 \subsection[DsExpr-literals]{Literals}
605 %************************************************************************
607 We give int/float literals type @Integer@ and @Rational@, respectively.
608 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
611 ToDo: put in range checks for when converting ``@i@''
612 (or should that be in the typechecker?)
614 For numeric literals, we try to detect there use at a standard type
615 (@Int@, @Float@, etc.) are directly put in the right constructor.
616 [NB: down with the @App@ conversion.]
618 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
621 dsLit :: HsLit -> DsM CoreExpr
622 dsLit (HsChar c) = returnDs (mkConApp charDataCon [mkLit (MachChar c)])
623 dsLit (HsCharPrim c) = returnDs (mkLit (MachChar c))
624 dsLit (HsString str) = mkStringLitFS str
625 dsLit (HsStringPrim s) = returnDs (mkLit (MachStr s))
626 dsLit (HsInteger i) = mkIntegerLit i
627 dsLit (HsInt i) = returnDs (mkConApp intDataCon [mkIntLit i])
628 dsLit (HsIntPrim i) = returnDs (mkIntLit i)
629 dsLit (HsFloatPrim f) = returnDs (mkLit (MachFloat f))
630 dsLit (HsDoublePrim d) = returnDs (mkLit (MachDouble d))
631 dsLit (HsLitLit str ty)
632 = ASSERT( maybeToBool maybe_ty )
633 returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
635 (maybe_ty, wrap_fn) = resultWrapper ty
636 Just rep_ty = maybe_ty
639 = mkIntegerLit (numerator r) `thenDs` \ num ->
640 mkIntegerLit (denominator r) `thenDs` \ denom ->
641 returnDs (mkConApp ratio_data_con [Type integer_ty, num, denom])
643 (ratio_data_con, integer_ty)
644 = case tcSplitTyConApp ty of
645 (tycon, [i_ty]) -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)
646 (head (tyConDataCons tycon), i_ty)