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, mkDsLets, 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(..) )
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 -- Silently ignore INLINE pragmas...
89 dsLet (MonoBind (AbsBinds [] [] binder_triples inlines
90 (PatMonoBind pat grhss loc)) sigs is_rec) body
91 | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
92 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
94 dsGuarded grhss `thenDs` \ rhs ->
96 body' = foldr bind body binder_triples
97 bind (tyvars, g, l) body = ASSERT( null tyvars )
98 bindNonRec g (Var l) body
100 mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat))
101 `thenDs` \ error_expr ->
102 matchSimply rhs PatBindRhs pat body' error_expr
104 result_ty = exprType body
106 -- Ordinary case for bindings
107 dsLet (MonoBind binds sigs is_rec) body
108 = dsMonoBinds NoSccs binds [] `thenDs` \ prs ->
110 Recursive -> returnDs (Let (Rec prs) body)
111 NonRecursive -> returnDs (mkDsLets [NonRec b r | (b,r) <- prs] body)
114 %************************************************************************
116 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
118 %************************************************************************
121 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
123 dsExpr (HsVar var) = returnDs (Var var)
124 dsExpr (HsIPVar var) = returnDs (Var var)
125 dsExpr (HsLit lit) = dsLit lit
126 -- HsOverLit has been gotten rid of by the type checker
128 dsExpr expr@(HsLam a_Match)
129 = matchWrapper LambdaExpr [a_Match] `thenDs` \ (binders, matching_code) ->
130 returnDs (mkLams binders matching_code)
132 dsExpr expr@(HsApp fun arg)
133 = dsExpr fun `thenDs` \ core_fun ->
134 dsExpr arg `thenDs` \ core_arg ->
135 returnDs (core_fun `App` core_arg)
138 Operator sections. At first it looks as if we can convert
147 But no! expr might be a redex, and we can lose laziness badly this
152 for example. So we convert instead to
154 let y = expr in \x -> op y x
156 If \tr{expr} is actually just a variable, say, then the simplifier
160 dsExpr (OpApp e1 op _ e2)
161 = dsExpr op `thenDs` \ core_op ->
162 -- for the type of y, we need the type of op's 2nd argument
163 dsExpr e1 `thenDs` \ x_core ->
164 dsExpr e2 `thenDs` \ y_core ->
165 returnDs (mkApps core_op [x_core, y_core])
167 dsExpr (SectionL expr op)
168 = dsExpr op `thenDs` \ core_op ->
169 -- for the type of y, we need the type of op's 2nd argument
171 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
172 -- Must look through an implicit-parameter type;
173 -- newtype impossible; hence Type.splitFunTys
175 dsExpr expr `thenDs` \ x_core ->
176 newSysLocalDs x_ty `thenDs` \ x_id ->
177 newSysLocalDs y_ty `thenDs` \ y_id ->
179 returnDs (bindNonRec x_id x_core $
180 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
182 -- dsExpr (SectionR op expr) -- \ x -> op x expr
183 dsExpr (SectionR op expr)
184 = dsExpr op `thenDs` \ core_op ->
185 -- for the type of x, we need the type of op's 2nd argument
187 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
188 -- See comment with SectionL
190 dsExpr expr `thenDs` \ y_core ->
191 newSysLocalDs x_ty `thenDs` \ x_id ->
192 newSysLocalDs y_ty `thenDs` \ y_id ->
194 returnDs (bindNonRec y_id y_core $
195 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
197 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
198 = mapDs dsExpr args `thenDs` \ core_args ->
199 dsCCall lbl core_args may_gc is_asm result_ty
200 -- dsCCall does all the unboxification, etc.
202 dsExpr (HsSCC cc expr)
203 = dsExpr expr `thenDs` \ core_expr ->
204 getModuleDs `thenDs` \ mod_name ->
205 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
207 -- special case to handle unboxed tuple patterns.
209 dsExpr (HsCase discrim matches src_loc)
210 | all ubx_tuple_match matches
211 = putSrcLocDs src_loc $
212 dsExpr discrim `thenDs` \ core_discrim ->
213 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
214 case matching_code of
215 Case (Var x) bndr alts | x == discrim_var ->
216 returnDs (Case core_discrim bndr alts)
217 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
219 ubx_tuple_match (Match _ [TuplePat ps Unboxed] _ _) = True
220 ubx_tuple_match _ = False
222 dsExpr (HsCase discrim matches src_loc)
223 = putSrcLocDs src_loc $
224 dsExpr discrim `thenDs` \ core_discrim ->
225 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
226 returnDs (bindNonRec discrim_var core_discrim matching_code)
228 dsExpr (HsLet binds body)
229 = dsExpr body `thenDs` \ body' ->
232 dsExpr (HsWith expr binds)
233 = dsExpr expr `thenDs` \ expr' ->
234 foldlDs dsIPBind expr' binds
237 = dsExpr e `thenDs` \ e' ->
238 returnDs (Let (NonRec n e') body)
240 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
241 | maybeToBool maybe_list_comp
242 = -- Special case for list comprehensions
243 putSrcLocDs src_loc $
244 dsListComp stmts elt_ty
247 = putSrcLocDs src_loc $
248 dsDo do_or_lc stmts return_id then_id fail_id result_ty
251 = case (do_or_lc, tcSplitTyConApp_maybe result_ty) of
252 (ListComp, Just (tycon, [elt_ty]))
256 -- We need the ListComp form to use deListComp (rather than the "do" form)
257 -- because the interpretation of ExprStmt depends on what sort of thing
260 Just elt_ty = maybe_list_comp
262 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
263 = putSrcLocDs src_loc $
264 dsExpr guard_expr `thenDs` \ core_guard ->
265 dsExpr then_expr `thenDs` \ core_then ->
266 dsExpr else_expr `thenDs` \ core_else ->
267 returnDs (mkIfThenElse core_guard core_then core_else)
272 \underline{\bf Type lambda and application}
273 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
275 dsExpr (TyLam tyvars expr)
276 = dsExpr expr `thenDs` \ core_expr ->
277 returnDs (mkLams tyvars core_expr)
279 dsExpr (TyApp expr tys)
280 = dsExpr expr `thenDs` \ core_expr ->
281 returnDs (mkTyApps core_expr tys)
286 \underline{\bf Various data construction things}
287 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
289 dsExpr (ExplicitList ty xs)
292 go [] = returnDs (mkNilExpr ty)
293 go (x:xs) = dsExpr x `thenDs` \ core_x ->
294 go xs `thenDs` \ core_xs ->
295 returnDs (mkConsExpr ty core_x core_xs)
297 dsExpr (ExplicitTuple expr_list boxity)
298 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
299 returnDs (mkConApp (tupleCon boxity (length expr_list))
300 (map (Type . exprType) core_exprs ++ core_exprs))
302 dsExpr (ArithSeqOut expr (From from))
303 = dsExpr expr `thenDs` \ expr2 ->
304 dsExpr from `thenDs` \ from2 ->
305 returnDs (App expr2 from2)
307 dsExpr (ArithSeqOut expr (FromTo from two))
308 = dsExpr expr `thenDs` \ expr2 ->
309 dsExpr from `thenDs` \ from2 ->
310 dsExpr two `thenDs` \ two2 ->
311 returnDs (mkApps expr2 [from2, two2])
313 dsExpr (ArithSeqOut expr (FromThen from thn))
314 = dsExpr expr `thenDs` \ expr2 ->
315 dsExpr from `thenDs` \ from2 ->
316 dsExpr thn `thenDs` \ thn2 ->
317 returnDs (mkApps expr2 [from2, thn2])
319 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
320 = dsExpr expr `thenDs` \ expr2 ->
321 dsExpr from `thenDs` \ from2 ->
322 dsExpr thn `thenDs` \ thn2 ->
323 dsExpr two `thenDs` \ two2 ->
324 returnDs (mkApps expr2 [from2, thn2, two2])
328 \underline{\bf Record construction and update}
329 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
330 For record construction we do this (assuming T has three arguments)
334 let err = /\a -> recConErr a
335 T (recConErr t1 "M.lhs/230/op1")
337 (recConErr t1 "M.lhs/230/op3")
339 @recConErr@ then converts its arugment string into a proper message
340 before printing it as
342 M.lhs, line 230: missing field op1 was evaluated
345 We also handle @C{}@ as valid construction syntax for an unlabelled
346 constructor @C@, setting all of @C@'s fields to bottom.
349 dsExpr (RecordConOut data_con con_expr rbinds)
350 = dsExpr con_expr `thenDs` \ con_expr' ->
352 (arg_tys, _) = tcSplitFunTys (exprType con_expr')
353 -- A newtype in the corner should be opaque;
354 -- hence TcType.tcSplitFunTys
357 = case [rhs | (sel_id,rhs,_) <- rbinds,
358 lbl == recordSelectorFieldLabel sel_id] of
359 (rhs:rhss) -> ASSERT( null rhss )
361 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
362 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
364 labels = dataConFieldLabels data_con
368 then mapDs unlabelled_bottom arg_tys
369 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
370 `thenDs` \ con_args ->
372 returnDs (mkApps con_expr' con_args)
375 Record update is a little harder. Suppose we have the decl:
377 data T = T1 {op1, op2, op3 :: Int}
378 | T2 {op4, op2 :: Int}
381 Then we translate as follows:
387 T1 op1 _ op3 -> T1 op1 op2 op3
388 T2 op4 _ -> T2 op4 op2
389 other -> recUpdError "M.lhs/230"
391 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
392 RHSs, and do not generate a Core constructor application directly, because the constructor
393 might do some argument-evaluation first; and may have to throw away some
397 dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty dicts [])
400 dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty dicts rbinds)
401 = getSrcLocDs `thenDs` \ src_loc ->
402 dsExpr record_expr `thenDs` \ record_expr' ->
404 -- Desugar the rbinds, and generate let-bindings if
405 -- necessary so that we don't lose sharing
408 in_inst_tys = tcTyConAppArgs record_in_ty -- Newtype opaque
409 out_inst_tys = tcTyConAppArgs record_out_ty -- Newtype opaque
411 mk_val_arg field old_arg_id
412 = case [rhs | (sel_id, rhs, _) <- rbinds,
413 field == recordSelectorFieldLabel sel_id] of
414 (rhs:rest) -> ASSERT(null rest) rhs
415 [] -> HsVar old_arg_id
418 = newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
419 -- This call to dataConArgTys won't work for existentials
421 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
422 (dataConFieldLabels con) arg_ids
423 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConWrapId con))
428 returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
433 -- Record stuff doesn't work for existentials
434 ASSERT( all (not . isExistentialDataCon) data_cons )
436 -- It's important to generate the match with matchWrapper,
437 -- and the right hand sides with applications of the wrapper Id
438 -- so that everything works when we are doing fancy unboxing on the
439 -- constructor aguments.
440 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
441 matchWrapper RecUpd alts `thenDs` \ ([discrim_var], matching_code) ->
443 returnDs (bindNonRec discrim_var record_expr' matching_code)
446 updated_fields :: [FieldLabel]
447 updated_fields = [recordSelectorFieldLabel sel_id | (sel_id,_,_) <- rbinds]
449 -- Get the type constructor from the first field label,
450 -- so that we are sure it'll have all its DataCons
451 -- (In GHCI, it's possible that some TyCons may not have all
452 -- their constructors, in a module-loop situation.)
453 tycon = fieldLabelTyCon (head updated_fields)
454 data_cons = tyConDataCons tycon
455 cons_to_upd = filter has_all_fields data_cons
457 has_all_fields :: DataCon -> Bool
458 has_all_fields con_id
459 = all (`elem` con_fields) updated_fields
461 con_fields = dataConFieldLabels con_id
466 \underline{\bf Dictionary lambda and application}
467 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
468 @DictLam@ and @DictApp@ turn into the regular old things.
469 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
470 complicated; reminiscent of fully-applied constructors.
472 dsExpr (DictLam dictvars expr)
473 = dsExpr expr `thenDs` \ core_expr ->
474 returnDs (mkLams dictvars core_expr)
478 dsExpr (DictApp expr dicts) -- becomes a curried application
479 = dsExpr expr `thenDs` \ core_expr ->
480 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
486 -- HsSyn constructs that just shouldn't be here:
487 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
488 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
489 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
494 %--------------------------------------------------------------------
496 Basically does the translation given in the Haskell~1.3 report:
501 -> Id -- id for: return m
502 -> Id -- id for: (>>=) m
503 -> Id -- id for: fail m
504 -> Type -- Element type; the whole expression has type (m t)
507 dsDo do_or_lc stmts return_id then_id fail_id result_ty
509 (_, b_ty) = tcSplitAppTy result_ty -- result_ty must be of the form (m b)
510 is_do = case do_or_lc of
514 -- For ExprStmt, see the comments near HsExpr.Stmt about
515 -- exactly what ExprStmts mean!
517 -- In dsDo we can only see DoStmt and ListComp (no gaurds)
519 go [ResultStmt expr locn]
520 | is_do = do_expr expr locn
521 | otherwise = do_expr expr locn `thenDs` \ expr2 ->
522 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
524 go (ExprStmt expr a_ty locn : stmts)
525 | is_do -- Do expression
526 = do_expr expr locn `thenDs` \ expr2 ->
527 go stmts `thenDs` \ rest ->
528 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
529 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
530 Lam ignored_result_id rest])
532 | otherwise -- List comprehension
533 = do_expr expr locn `thenDs` \ expr2 ->
534 go stmts `thenDs` \ rest ->
536 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
538 mkStringLit msg `thenDs` \ core_msg ->
539 returnDs (mkIfThenElse expr2 rest
540 (App (App (Var fail_id) (Type b_ty)) core_msg))
542 go (LetStmt binds : stmts )
543 = go stmts `thenDs` \ rest ->
546 go (BindStmt pat expr locn : stmts)
548 dsExpr expr `thenDs` \ expr2 ->
550 a_ty = outPatType pat
551 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
552 (HsLit (HsString (_PK_ msg)))
553 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
554 main_match = mkSimpleMatch [pat]
555 (HsDoOut do_or_lc stmts return_id then_id
556 fail_id result_ty locn)
559 | failureFreePat pat = [main_match]
562 , mkSimpleMatch [WildPat a_ty] fail_expr result_ty locn
565 matchWrapper (DoCtxt do_or_lc) the_matches `thenDs` \ (binders, matching_code) ->
566 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
567 mkLams binders matching_code])
572 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
576 %************************************************************************
578 \subsection[DsExpr-literals]{Literals}
580 %************************************************************************
582 We give int/float literals type @Integer@ and @Rational@, respectively.
583 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
586 ToDo: put in range checks for when converting ``@i@''
587 (or should that be in the typechecker?)
589 For numeric literals, we try to detect there use at a standard type
590 (@Int@, @Float@, etc.) are directly put in the right constructor.
591 [NB: down with the @App@ conversion.]
593 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
596 dsLit :: HsLit -> DsM CoreExpr
597 dsLit (HsChar c) = returnDs (mkConApp charDataCon [mkLit (MachChar c)])
598 dsLit (HsCharPrim c) = returnDs (mkLit (MachChar c))
599 dsLit (HsString str) = mkStringLitFS str
600 dsLit (HsStringPrim s) = returnDs (mkLit (MachStr s))
601 dsLit (HsInteger i) = mkIntegerLit i
602 dsLit (HsInt i) = returnDs (mkConApp intDataCon [mkIntLit i])
603 dsLit (HsIntPrim i) = returnDs (mkIntLit i)
604 dsLit (HsFloatPrim f) = returnDs (mkLit (MachFloat f))
605 dsLit (HsDoublePrim d) = returnDs (mkLit (MachDouble d))
606 dsLit (HsLitLit str ty)
607 = ASSERT( maybeToBool maybe_ty )
608 returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
610 (maybe_ty, wrap_fn) = resultWrapper ty
611 Just rep_ty = maybe_ty
614 = mkIntegerLit (numerator r) `thenDs` \ num ->
615 mkIntegerLit (denominator r) `thenDs` \ denom ->
616 returnDs (mkConApp ratio_data_con [Type integer_ty, num, denom])
618 (ratio_data_con, integer_ty)
619 = case tcSplitTyConApp ty of
620 (tycon, [i_ty]) -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)
621 (head (tyConDataCons tycon), i_ty)