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 Type ( ipNameName )
49 import TyCon ( tyConDataCons )
50 import TysWiredIn ( tupleCon, listTyCon, charDataCon, intDataCon )
51 import BasicTypes ( RecFlag(..), Boxity(..) )
52 import Maybes ( maybeToBool )
53 import PrelNames ( hasKey, ratioTyConKey )
54 import Util ( zipEqual, zipWithEqual )
57 import Ratio ( numerator, denominator )
61 %************************************************************************
65 %************************************************************************
67 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
68 and transforming it into one for the let-bindings enclosing the body.
70 This may seem a bit odd, but (source) let bindings can contain unboxed
75 This must be transformed to a case expression and, if the type has
76 more than one constructor, may fail.
79 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
84 dsLet (ThenBinds b1 b2) body
85 = dsLet b2 body `thenDs` \ body' ->
88 -- Special case for bindings which bind unlifted variables
89 -- We need to do a case right away, rather than building
90 -- a tuple and doing selections.
91 -- Silently ignore INLINE pragmas...
92 dsLet (MonoBind (AbsBinds [] [] exports inlines binds) sigs is_rec) body
93 | or [isUnLiftedType (idType g) | (_, g, l) <- exports]
94 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
95 -- Unlifted bindings are always non-recursive
96 -- and are always a Fun or Pat monobind
98 -- ToDo: in some bizarre case it's conceivable that there
99 -- could be dict binds in the 'binds'. (See the notes
100 -- below. Then pattern-match would fail. Urk.)
102 FunMonoBind fun _ matches loc
104 matchWrapper (FunRhs fun) matches `thenDs` \ (args, rhs) ->
105 ASSERT( null args ) -- Functions aren't lifted
106 returnDs (bindNonRec fun rhs body_w_exports)
108 PatMonoBind pat grhss loc
110 dsGuarded grhss `thenDs` \ rhs ->
111 mk_error_app pat `thenDs` \ error_expr ->
112 matchSimply rhs PatBindRhs pat body_w_exports error_expr
114 body_w_exports = foldr bind_export body exports
115 bind_export (tvs, g, l) body = ASSERT( null tvs )
116 bindNonRec g (Var l) body
118 mk_error_app pat = mkErrorAppDs iRREFUT_PAT_ERROR_ID
122 -- Ordinary case for bindings
123 dsLet (MonoBind binds sigs is_rec) body
124 = dsMonoBinds NoSccs binds [] `thenDs` \ prs ->
125 returnDs (Let (Rec prs) body)
126 -- Use a Rec regardless of is_rec.
127 -- Why? Because it allows the MonoBinds to be all
128 -- mixed up, which is what happens in one rare case
129 -- Namely, for an AbsBind with no tyvars and no dicts,
130 -- but which does have dictionary bindings.
131 -- See notes with TcSimplify.inferLoop [NO TYVARS]
132 -- It turned out that wrapping a Rec here was the easiest solution
134 -- NB The previous case dealt with unlifted bindings, so we
135 -- only have to deal with lifted ones now; so Rec is ok
138 %************************************************************************
140 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
142 %************************************************************************
145 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
147 dsExpr (HsVar var) = returnDs (Var var)
148 dsExpr (HsIPVar ip) = returnDs (Var (ipNameName ip))
149 dsExpr (HsLit lit) = dsLit lit
150 -- HsOverLit has been gotten rid of by the type checker
152 dsExpr expr@(HsLam a_Match)
153 = matchWrapper LambdaExpr [a_Match] `thenDs` \ (binders, matching_code) ->
154 returnDs (mkLams binders matching_code)
156 dsExpr expr@(HsApp fun arg)
157 = dsExpr fun `thenDs` \ core_fun ->
158 dsExpr arg `thenDs` \ core_arg ->
159 returnDs (core_fun `App` core_arg)
162 Operator sections. At first it looks as if we can convert
171 But no! expr might be a redex, and we can lose laziness badly this
176 for example. So we convert instead to
178 let y = expr in \x -> op y x
180 If \tr{expr} is actually just a variable, say, then the simplifier
184 dsExpr (OpApp e1 op _ e2)
185 = dsExpr op `thenDs` \ core_op ->
186 -- for the type of y, we need the type of op's 2nd argument
187 dsExpr e1 `thenDs` \ x_core ->
188 dsExpr e2 `thenDs` \ y_core ->
189 returnDs (mkApps core_op [x_core, y_core])
191 dsExpr (SectionL expr op)
192 = dsExpr op `thenDs` \ core_op ->
193 -- for the type of y, we need the type of op's 2nd argument
195 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
196 -- Must look through an implicit-parameter type;
197 -- newtype impossible; hence Type.splitFunTys
199 dsExpr expr `thenDs` \ x_core ->
200 newSysLocalDs x_ty `thenDs` \ x_id ->
201 newSysLocalDs y_ty `thenDs` \ y_id ->
203 returnDs (bindNonRec x_id x_core $
204 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
206 -- dsExpr (SectionR op expr) -- \ x -> op x expr
207 dsExpr (SectionR op expr)
208 = dsExpr op `thenDs` \ core_op ->
209 -- for the type of x, we need the type of op's 2nd argument
211 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
212 -- See comment with SectionL
214 dsExpr expr `thenDs` \ y_core ->
215 newSysLocalDs x_ty `thenDs` \ x_id ->
216 newSysLocalDs y_ty `thenDs` \ y_id ->
218 returnDs (bindNonRec y_id y_core $
219 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
221 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
222 = mapDs dsExpr args `thenDs` \ core_args ->
223 dsCCall lbl core_args may_gc is_asm result_ty
224 -- dsCCall does all the unboxification, etc.
226 dsExpr (HsSCC cc expr)
227 = dsExpr expr `thenDs` \ core_expr ->
228 getModuleDs `thenDs` \ mod_name ->
229 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
231 -- special case to handle unboxed tuple patterns.
233 dsExpr (HsCase discrim matches src_loc)
234 | all ubx_tuple_match matches
235 = putSrcLocDs src_loc $
236 dsExpr discrim `thenDs` \ core_discrim ->
237 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
238 case matching_code of
239 Case (Var x) bndr alts | x == discrim_var ->
240 returnDs (Case core_discrim bndr alts)
241 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
243 ubx_tuple_match (Match [TuplePat ps Unboxed] _ _) = True
244 ubx_tuple_match _ = False
246 dsExpr (HsCase discrim matches src_loc)
247 = putSrcLocDs src_loc $
248 dsExpr discrim `thenDs` \ core_discrim ->
249 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
250 returnDs (bindNonRec discrim_var core_discrim matching_code)
252 dsExpr (HsLet binds body)
253 = dsExpr body `thenDs` \ body' ->
256 dsExpr (HsWith expr binds)
257 = dsExpr expr `thenDs` \ expr' ->
258 foldlDs dsIPBind expr' binds
261 = dsExpr e `thenDs` \ e' ->
262 returnDs (Let (NonRec (ipNameName n) e') body)
264 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
265 | maybeToBool maybe_list_comp
266 = -- Special case for list comprehensions
267 putSrcLocDs src_loc $
268 dsListComp stmts elt_ty
271 = putSrcLocDs src_loc $
272 dsDo do_or_lc stmts return_id then_id fail_id result_ty
275 = case (do_or_lc, tcSplitTyConApp_maybe result_ty) of
276 (ListComp, Just (tycon, [elt_ty]))
280 -- We need the ListComp form to use deListComp (rather than the "do" form)
281 -- because the interpretation of ExprStmt depends on what sort of thing
284 Just elt_ty = maybe_list_comp
286 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
287 = putSrcLocDs src_loc $
288 dsExpr guard_expr `thenDs` \ core_guard ->
289 dsExpr then_expr `thenDs` \ core_then ->
290 dsExpr else_expr `thenDs` \ core_else ->
291 returnDs (mkIfThenElse core_guard core_then core_else)
296 \underline{\bf Type lambda and application}
297 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
299 dsExpr (TyLam tyvars expr)
300 = dsExpr expr `thenDs` \ core_expr ->
301 returnDs (mkLams tyvars core_expr)
303 dsExpr (TyApp expr tys)
304 = dsExpr expr `thenDs` \ core_expr ->
305 returnDs (mkTyApps core_expr tys)
310 \underline{\bf Various data construction things}
311 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
313 dsExpr (ExplicitList ty xs)
316 go [] = returnDs (mkNilExpr ty)
317 go (x:xs) = dsExpr x `thenDs` \ core_x ->
318 go xs `thenDs` \ core_xs ->
319 returnDs (mkConsExpr ty core_x core_xs)
321 dsExpr (ExplicitTuple expr_list boxity)
322 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
323 returnDs (mkConApp (tupleCon boxity (length expr_list))
324 (map (Type . exprType) core_exprs ++ core_exprs))
326 dsExpr (ArithSeqOut expr (From from))
327 = dsExpr expr `thenDs` \ expr2 ->
328 dsExpr from `thenDs` \ from2 ->
329 returnDs (App expr2 from2)
331 dsExpr (ArithSeqOut expr (FromTo from two))
332 = dsExpr expr `thenDs` \ expr2 ->
333 dsExpr from `thenDs` \ from2 ->
334 dsExpr two `thenDs` \ two2 ->
335 returnDs (mkApps expr2 [from2, two2])
337 dsExpr (ArithSeqOut expr (FromThen from thn))
338 = dsExpr expr `thenDs` \ expr2 ->
339 dsExpr from `thenDs` \ from2 ->
340 dsExpr thn `thenDs` \ thn2 ->
341 returnDs (mkApps expr2 [from2, thn2])
343 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
344 = dsExpr expr `thenDs` \ expr2 ->
345 dsExpr from `thenDs` \ from2 ->
346 dsExpr thn `thenDs` \ thn2 ->
347 dsExpr two `thenDs` \ two2 ->
348 returnDs (mkApps expr2 [from2, thn2, two2])
352 \underline{\bf Record construction and update}
353 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
354 For record construction we do this (assuming T has three arguments)
358 let err = /\a -> recConErr a
359 T (recConErr t1 "M.lhs/230/op1")
361 (recConErr t1 "M.lhs/230/op3")
363 @recConErr@ then converts its arugment string into a proper message
364 before printing it as
366 M.lhs, line 230: missing field op1 was evaluated
369 We also handle @C{}@ as valid construction syntax for an unlabelled
370 constructor @C@, setting all of @C@'s fields to bottom.
373 dsExpr (RecordConOut data_con con_expr rbinds)
374 = dsExpr con_expr `thenDs` \ con_expr' ->
376 (arg_tys, _) = tcSplitFunTys (exprType con_expr')
377 -- A newtype in the corner should be opaque;
378 -- hence TcType.tcSplitFunTys
381 = case [rhs | (sel_id,rhs,_) <- rbinds,
382 lbl == recordSelectorFieldLabel sel_id] of
383 (rhs:rhss) -> ASSERT( null rhss )
385 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
386 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
388 labels = dataConFieldLabels data_con
392 then mapDs unlabelled_bottom arg_tys
393 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
394 `thenDs` \ con_args ->
396 returnDs (mkApps con_expr' con_args)
399 Record update is a little harder. Suppose we have the decl:
401 data T = T1 {op1, op2, op3 :: Int}
402 | T2 {op4, op2 :: Int}
405 Then we translate as follows:
411 T1 op1 _ op3 -> T1 op1 op2 op3
412 T2 op4 _ -> T2 op4 op2
413 other -> recUpdError "M.lhs/230"
415 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
416 RHSs, and do not generate a Core constructor application directly, because the constructor
417 might do some argument-evaluation first; and may have to throw away some
421 dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty dicts [])
424 dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty dicts rbinds)
425 = getSrcLocDs `thenDs` \ src_loc ->
426 dsExpr record_expr `thenDs` \ record_expr' ->
428 -- Desugar the rbinds, and generate let-bindings if
429 -- necessary so that we don't lose sharing
432 in_inst_tys = tcTyConAppArgs record_in_ty -- Newtype opaque
433 out_inst_tys = tcTyConAppArgs record_out_ty -- Newtype opaque
435 mk_val_arg field old_arg_id
436 = case [rhs | (sel_id, rhs, _) <- rbinds,
437 field == recordSelectorFieldLabel sel_id] of
438 (rhs:rest) -> ASSERT(null rest) rhs
439 [] -> HsVar old_arg_id
442 = newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
443 -- This call to dataConArgTys won't work for existentials
445 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
446 (dataConFieldLabels con) arg_ids
447 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConWrapId con))
452 returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
457 -- Record stuff doesn't work for existentials
458 ASSERT( all (not . isExistentialDataCon) data_cons )
460 -- It's important to generate the match with matchWrapper,
461 -- and the right hand sides with applications of the wrapper Id
462 -- so that everything works when we are doing fancy unboxing on the
463 -- constructor aguments.
464 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
465 matchWrapper RecUpd alts `thenDs` \ ([discrim_var], matching_code) ->
467 returnDs (bindNonRec discrim_var record_expr' matching_code)
470 updated_fields :: [FieldLabel]
471 updated_fields = [recordSelectorFieldLabel sel_id | (sel_id,_,_) <- rbinds]
473 -- Get the type constructor from the first field label,
474 -- so that we are sure it'll have all its DataCons
475 -- (In GHCI, it's possible that some TyCons may not have all
476 -- their constructors, in a module-loop situation.)
477 tycon = fieldLabelTyCon (head updated_fields)
478 data_cons = tyConDataCons tycon
479 cons_to_upd = filter has_all_fields data_cons
481 has_all_fields :: DataCon -> Bool
482 has_all_fields con_id
483 = all (`elem` con_fields) updated_fields
485 con_fields = dataConFieldLabels con_id
490 \underline{\bf Dictionary lambda and application}
491 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
492 @DictLam@ and @DictApp@ turn into the regular old things.
493 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
494 complicated; reminiscent of fully-applied constructors.
496 dsExpr (DictLam dictvars expr)
497 = dsExpr expr `thenDs` \ core_expr ->
498 returnDs (mkLams dictvars core_expr)
502 dsExpr (DictApp expr dicts) -- becomes a curried application
503 = dsExpr expr `thenDs` \ core_expr ->
504 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
510 -- HsSyn constructs that just shouldn't be here:
511 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
512 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
513 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
518 %--------------------------------------------------------------------
520 Basically does the translation given in the Haskell~1.3 report:
525 -> Id -- id for: return m
526 -> Id -- id for: (>>=) m
527 -> Id -- id for: fail m
528 -> Type -- Element type; the whole expression has type (m t)
531 dsDo do_or_lc stmts return_id then_id fail_id result_ty
533 (_, b_ty) = tcSplitAppTy result_ty -- result_ty must be of the form (m b)
534 is_do = case do_or_lc of
538 -- For ExprStmt, see the comments near HsExpr.Stmt about
539 -- exactly what ExprStmts mean!
541 -- In dsDo we can only see DoStmt and ListComp (no gaurds)
543 go [ResultStmt expr locn]
544 | is_do = do_expr expr locn
545 | otherwise = do_expr expr locn `thenDs` \ expr2 ->
546 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
548 go (ExprStmt expr a_ty locn : stmts)
549 | is_do -- Do expression
550 = do_expr expr locn `thenDs` \ expr2 ->
551 go stmts `thenDs` \ rest ->
552 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
553 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
554 Lam ignored_result_id rest])
556 | otherwise -- List comprehension
557 = do_expr expr locn `thenDs` \ expr2 ->
558 go stmts `thenDs` \ rest ->
560 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
562 mkStringLit msg `thenDs` \ core_msg ->
563 returnDs (mkIfThenElse expr2 rest
564 (App (App (Var fail_id) (Type b_ty)) core_msg))
566 go (LetStmt binds : stmts )
567 = go stmts `thenDs` \ rest ->
570 go (BindStmt pat expr locn : stmts)
572 dsExpr expr `thenDs` \ expr2 ->
574 a_ty = outPatType pat
575 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
576 (HsLit (HsString (_PK_ msg)))
577 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
578 main_match = mkSimpleMatch [pat]
579 (HsDoOut do_or_lc stmts return_id then_id
580 fail_id result_ty locn)
583 | failureFreePat pat = [main_match]
586 , mkSimpleMatch [WildPat a_ty] fail_expr result_ty locn
589 matchWrapper (DoCtxt do_or_lc) the_matches `thenDs` \ (binders, matching_code) ->
590 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
591 mkLams binders matching_code])
596 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
600 %************************************************************************
602 \subsection[DsExpr-literals]{Literals}
604 %************************************************************************
606 We give int/float literals type @Integer@ and @Rational@, respectively.
607 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
610 ToDo: put in range checks for when converting ``@i@''
611 (or should that be in the typechecker?)
613 For numeric literals, we try to detect there use at a standard type
614 (@Int@, @Float@, etc.) are directly put in the right constructor.
615 [NB: down with the @App@ conversion.]
617 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
620 dsLit :: HsLit -> DsM CoreExpr
621 dsLit (HsChar c) = returnDs (mkConApp charDataCon [mkLit (MachChar c)])
622 dsLit (HsCharPrim c) = returnDs (mkLit (MachChar c))
623 dsLit (HsString str) = mkStringLitFS str
624 dsLit (HsStringPrim s) = returnDs (mkLit (MachStr s))
625 dsLit (HsInteger i) = mkIntegerLit i
626 dsLit (HsInt i) = returnDs (mkConApp intDataCon [mkIntLit i])
627 dsLit (HsIntPrim i) = returnDs (mkIntLit i)
628 dsLit (HsFloatPrim f) = returnDs (mkLit (MachFloat f))
629 dsLit (HsDoublePrim d) = returnDs (mkLit (MachDouble d))
630 dsLit (HsLitLit str ty)
631 = ASSERT( maybeToBool maybe_ty )
632 returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
634 (maybe_ty, wrap_fn) = resultWrapper ty
635 Just rep_ty = maybe_ty
638 = mkIntegerLit (numerator r) `thenDs` \ num ->
639 mkIntegerLit (denominator r) `thenDs` \ denom ->
640 returnDs (mkConApp ratio_data_con [Type integer_ty, num, denom])
642 (ratio_data_con, integer_ty)
643 = case tcSplitTyConApp ty of
644 (tycon, [i_ty]) -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)
645 (head (tyConDataCons tycon), i_ty)