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(..) )
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 ->
109 returnDs (Let (Rec prs) body)
110 -- Use a Rec regardless of is_rec.
111 -- Why? Because it allows the MonoBinds to be all
112 -- mixed up, which is what happens in one rare case
113 -- Namely, for an AbsBind with no tyvars and no dicts,
114 -- but which does have dictionary bindings.
115 -- See notes with TcSimplify.inferLoop [NO TYVARS]
116 -- It turned out that wrapping a Rec here was the easiest solution
119 %************************************************************************
121 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
123 %************************************************************************
126 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
128 dsExpr (HsVar var) = returnDs (Var var)
129 dsExpr (HsIPVar var) = returnDs (Var var)
130 dsExpr (HsLit lit) = dsLit lit
131 -- HsOverLit has been gotten rid of by the type checker
133 dsExpr expr@(HsLam a_Match)
134 = matchWrapper LambdaExpr [a_Match] `thenDs` \ (binders, matching_code) ->
135 returnDs (mkLams binders matching_code)
137 dsExpr expr@(HsApp fun arg)
138 = dsExpr fun `thenDs` \ core_fun ->
139 dsExpr arg `thenDs` \ core_arg ->
140 returnDs (core_fun `App` core_arg)
143 Operator sections. At first it looks as if we can convert
152 But no! expr might be a redex, and we can lose laziness badly this
157 for example. So we convert instead to
159 let y = expr in \x -> op y x
161 If \tr{expr} is actually just a variable, say, then the simplifier
165 dsExpr (OpApp e1 op _ e2)
166 = dsExpr op `thenDs` \ core_op ->
167 -- for the type of y, we need the type of op's 2nd argument
168 dsExpr e1 `thenDs` \ x_core ->
169 dsExpr e2 `thenDs` \ y_core ->
170 returnDs (mkApps core_op [x_core, y_core])
172 dsExpr (SectionL expr op)
173 = dsExpr op `thenDs` \ core_op ->
174 -- for the type of y, we need the type of op's 2nd argument
176 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
177 -- Must look through an implicit-parameter type;
178 -- newtype impossible; hence Type.splitFunTys
180 dsExpr expr `thenDs` \ x_core ->
181 newSysLocalDs x_ty `thenDs` \ x_id ->
182 newSysLocalDs y_ty `thenDs` \ y_id ->
184 returnDs (bindNonRec x_id x_core $
185 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
187 -- dsExpr (SectionR op expr) -- \ x -> op x expr
188 dsExpr (SectionR op expr)
189 = dsExpr op `thenDs` \ core_op ->
190 -- for the type of x, we need the type of op's 2nd argument
192 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
193 -- See comment with SectionL
195 dsExpr expr `thenDs` \ y_core ->
196 newSysLocalDs x_ty `thenDs` \ x_id ->
197 newSysLocalDs y_ty `thenDs` \ y_id ->
199 returnDs (bindNonRec y_id y_core $
200 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
202 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
203 = mapDs dsExpr args `thenDs` \ core_args ->
204 dsCCall lbl core_args may_gc is_asm result_ty
205 -- dsCCall does all the unboxification, etc.
207 dsExpr (HsSCC cc expr)
208 = dsExpr expr `thenDs` \ core_expr ->
209 getModuleDs `thenDs` \ mod_name ->
210 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
212 -- special case to handle unboxed tuple patterns.
214 dsExpr (HsCase discrim matches src_loc)
215 | all ubx_tuple_match matches
216 = putSrcLocDs src_loc $
217 dsExpr discrim `thenDs` \ core_discrim ->
218 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
219 case matching_code of
220 Case (Var x) bndr alts | x == discrim_var ->
221 returnDs (Case core_discrim bndr alts)
222 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
224 ubx_tuple_match (Match _ [TuplePat ps Unboxed] _ _) = True
225 ubx_tuple_match _ = False
227 dsExpr (HsCase discrim matches src_loc)
228 = putSrcLocDs src_loc $
229 dsExpr discrim `thenDs` \ core_discrim ->
230 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
231 returnDs (bindNonRec discrim_var core_discrim matching_code)
233 dsExpr (HsLet binds body)
234 = dsExpr body `thenDs` \ body' ->
237 dsExpr (HsWith expr binds)
238 = dsExpr expr `thenDs` \ expr' ->
239 foldlDs dsIPBind expr' binds
242 = dsExpr e `thenDs` \ e' ->
243 returnDs (Let (NonRec n e') body)
245 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
246 | maybeToBool maybe_list_comp
247 = -- Special case for list comprehensions
248 putSrcLocDs src_loc $
249 dsListComp stmts elt_ty
252 = putSrcLocDs src_loc $
253 dsDo do_or_lc stmts return_id then_id fail_id result_ty
256 = case (do_or_lc, tcSplitTyConApp_maybe result_ty) of
257 (ListComp, Just (tycon, [elt_ty]))
261 -- We need the ListComp form to use deListComp (rather than the "do" form)
262 -- because the interpretation of ExprStmt depends on what sort of thing
265 Just elt_ty = maybe_list_comp
267 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
268 = putSrcLocDs src_loc $
269 dsExpr guard_expr `thenDs` \ core_guard ->
270 dsExpr then_expr `thenDs` \ core_then ->
271 dsExpr else_expr `thenDs` \ core_else ->
272 returnDs (mkIfThenElse core_guard core_then core_else)
277 \underline{\bf Type lambda and application}
278 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
280 dsExpr (TyLam tyvars expr)
281 = dsExpr expr `thenDs` \ core_expr ->
282 returnDs (mkLams tyvars core_expr)
284 dsExpr (TyApp expr tys)
285 = dsExpr expr `thenDs` \ core_expr ->
286 returnDs (mkTyApps core_expr tys)
291 \underline{\bf Various data construction things}
292 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
294 dsExpr (ExplicitList ty xs)
297 go [] = returnDs (mkNilExpr ty)
298 go (x:xs) = dsExpr x `thenDs` \ core_x ->
299 go xs `thenDs` \ core_xs ->
300 returnDs (mkConsExpr ty core_x core_xs)
302 dsExpr (ExplicitTuple expr_list boxity)
303 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
304 returnDs (mkConApp (tupleCon boxity (length expr_list))
305 (map (Type . exprType) core_exprs ++ core_exprs))
307 dsExpr (ArithSeqOut expr (From from))
308 = dsExpr expr `thenDs` \ expr2 ->
309 dsExpr from `thenDs` \ from2 ->
310 returnDs (App expr2 from2)
312 dsExpr (ArithSeqOut expr (FromTo from two))
313 = dsExpr expr `thenDs` \ expr2 ->
314 dsExpr from `thenDs` \ from2 ->
315 dsExpr two `thenDs` \ two2 ->
316 returnDs (mkApps expr2 [from2, two2])
318 dsExpr (ArithSeqOut expr (FromThen from thn))
319 = dsExpr expr `thenDs` \ expr2 ->
320 dsExpr from `thenDs` \ from2 ->
321 dsExpr thn `thenDs` \ thn2 ->
322 returnDs (mkApps expr2 [from2, thn2])
324 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
325 = dsExpr expr `thenDs` \ expr2 ->
326 dsExpr from `thenDs` \ from2 ->
327 dsExpr thn `thenDs` \ thn2 ->
328 dsExpr two `thenDs` \ two2 ->
329 returnDs (mkApps expr2 [from2, thn2, two2])
333 \underline{\bf Record construction and update}
334 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
335 For record construction we do this (assuming T has three arguments)
339 let err = /\a -> recConErr a
340 T (recConErr t1 "M.lhs/230/op1")
342 (recConErr t1 "M.lhs/230/op3")
344 @recConErr@ then converts its arugment string into a proper message
345 before printing it as
347 M.lhs, line 230: missing field op1 was evaluated
350 We also handle @C{}@ as valid construction syntax for an unlabelled
351 constructor @C@, setting all of @C@'s fields to bottom.
354 dsExpr (RecordConOut data_con con_expr rbinds)
355 = dsExpr con_expr `thenDs` \ con_expr' ->
357 (arg_tys, _) = tcSplitFunTys (exprType con_expr')
358 -- A newtype in the corner should be opaque;
359 -- hence TcType.tcSplitFunTys
362 = case [rhs | (sel_id,rhs,_) <- rbinds,
363 lbl == recordSelectorFieldLabel sel_id] of
364 (rhs:rhss) -> ASSERT( null rhss )
366 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
367 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
369 labels = dataConFieldLabels data_con
373 then mapDs unlabelled_bottom arg_tys
374 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
375 `thenDs` \ con_args ->
377 returnDs (mkApps con_expr' con_args)
380 Record update is a little harder. Suppose we have the decl:
382 data T = T1 {op1, op2, op3 :: Int}
383 | T2 {op4, op2 :: Int}
386 Then we translate as follows:
392 T1 op1 _ op3 -> T1 op1 op2 op3
393 T2 op4 _ -> T2 op4 op2
394 other -> recUpdError "M.lhs/230"
396 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
397 RHSs, and do not generate a Core constructor application directly, because the constructor
398 might do some argument-evaluation first; and may have to throw away some
402 dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty dicts [])
405 dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty dicts rbinds)
406 = getSrcLocDs `thenDs` \ src_loc ->
407 dsExpr record_expr `thenDs` \ record_expr' ->
409 -- Desugar the rbinds, and generate let-bindings if
410 -- necessary so that we don't lose sharing
413 in_inst_tys = tcTyConAppArgs record_in_ty -- Newtype opaque
414 out_inst_tys = tcTyConAppArgs record_out_ty -- Newtype opaque
416 mk_val_arg field old_arg_id
417 = case [rhs | (sel_id, rhs, _) <- rbinds,
418 field == recordSelectorFieldLabel sel_id] of
419 (rhs:rest) -> ASSERT(null rest) rhs
420 [] -> HsVar old_arg_id
423 = newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
424 -- This call to dataConArgTys won't work for existentials
426 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
427 (dataConFieldLabels con) arg_ids
428 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConWrapId con))
433 returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
438 -- Record stuff doesn't work for existentials
439 ASSERT( all (not . isExistentialDataCon) data_cons )
441 -- It's important to generate the match with matchWrapper,
442 -- and the right hand sides with applications of the wrapper Id
443 -- so that everything works when we are doing fancy unboxing on the
444 -- constructor aguments.
445 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
446 matchWrapper RecUpd alts `thenDs` \ ([discrim_var], matching_code) ->
448 returnDs (bindNonRec discrim_var record_expr' matching_code)
451 updated_fields :: [FieldLabel]
452 updated_fields = [recordSelectorFieldLabel sel_id | (sel_id,_,_) <- rbinds]
454 -- Get the type constructor from the first field label,
455 -- so that we are sure it'll have all its DataCons
456 -- (In GHCI, it's possible that some TyCons may not have all
457 -- their constructors, in a module-loop situation.)
458 tycon = fieldLabelTyCon (head updated_fields)
459 data_cons = tyConDataCons tycon
460 cons_to_upd = filter has_all_fields data_cons
462 has_all_fields :: DataCon -> Bool
463 has_all_fields con_id
464 = all (`elem` con_fields) updated_fields
466 con_fields = dataConFieldLabels con_id
471 \underline{\bf Dictionary lambda and application}
472 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
473 @DictLam@ and @DictApp@ turn into the regular old things.
474 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
475 complicated; reminiscent of fully-applied constructors.
477 dsExpr (DictLam dictvars expr)
478 = dsExpr expr `thenDs` \ core_expr ->
479 returnDs (mkLams dictvars core_expr)
483 dsExpr (DictApp expr dicts) -- becomes a curried application
484 = dsExpr expr `thenDs` \ core_expr ->
485 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
491 -- HsSyn constructs that just shouldn't be here:
492 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
493 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
494 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
499 %--------------------------------------------------------------------
501 Basically does the translation given in the Haskell~1.3 report:
506 -> Id -- id for: return m
507 -> Id -- id for: (>>=) m
508 -> Id -- id for: fail m
509 -> Type -- Element type; the whole expression has type (m t)
512 dsDo do_or_lc stmts return_id then_id fail_id result_ty
514 (_, b_ty) = tcSplitAppTy result_ty -- result_ty must be of the form (m b)
515 is_do = case do_or_lc of
519 -- For ExprStmt, see the comments near HsExpr.Stmt about
520 -- exactly what ExprStmts mean!
522 -- In dsDo we can only see DoStmt and ListComp (no gaurds)
524 go [ResultStmt expr locn]
525 | is_do = do_expr expr locn
526 | otherwise = do_expr expr locn `thenDs` \ expr2 ->
527 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
529 go (ExprStmt expr a_ty locn : stmts)
530 | is_do -- Do expression
531 = do_expr expr locn `thenDs` \ expr2 ->
532 go stmts `thenDs` \ rest ->
533 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
534 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
535 Lam ignored_result_id rest])
537 | otherwise -- List comprehension
538 = do_expr expr locn `thenDs` \ expr2 ->
539 go stmts `thenDs` \ rest ->
541 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
543 mkStringLit msg `thenDs` \ core_msg ->
544 returnDs (mkIfThenElse expr2 rest
545 (App (App (Var fail_id) (Type b_ty)) core_msg))
547 go (LetStmt binds : stmts )
548 = go stmts `thenDs` \ rest ->
551 go (BindStmt pat expr locn : stmts)
553 dsExpr expr `thenDs` \ expr2 ->
555 a_ty = outPatType pat
556 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
557 (HsLit (HsString (_PK_ msg)))
558 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
559 main_match = mkSimpleMatch [pat]
560 (HsDoOut do_or_lc stmts return_id then_id
561 fail_id result_ty locn)
564 | failureFreePat pat = [main_match]
567 , mkSimpleMatch [WildPat a_ty] fail_expr result_ty locn
570 matchWrapper (DoCtxt do_or_lc) the_matches `thenDs` \ (binders, matching_code) ->
571 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
572 mkLams binders matching_code])
577 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
581 %************************************************************************
583 \subsection[DsExpr-literals]{Literals}
585 %************************************************************************
587 We give int/float literals type @Integer@ and @Rational@, respectively.
588 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
591 ToDo: put in range checks for when converting ``@i@''
592 (or should that be in the typechecker?)
594 For numeric literals, we try to detect there use at a standard type
595 (@Int@, @Float@, etc.) are directly put in the right constructor.
596 [NB: down with the @App@ conversion.]
598 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
601 dsLit :: HsLit -> DsM CoreExpr
602 dsLit (HsChar c) = returnDs (mkConApp charDataCon [mkLit (MachChar c)])
603 dsLit (HsCharPrim c) = returnDs (mkLit (MachChar c))
604 dsLit (HsString str) = mkStringLitFS str
605 dsLit (HsStringPrim s) = returnDs (mkLit (MachStr s))
606 dsLit (HsInteger i) = mkIntegerLit i
607 dsLit (HsInt i) = returnDs (mkConApp intDataCon [mkIntLit i])
608 dsLit (HsIntPrim i) = returnDs (mkIntLit i)
609 dsLit (HsFloatPrim f) = returnDs (mkLit (MachFloat f))
610 dsLit (HsDoublePrim d) = returnDs (mkLit (MachDouble d))
611 dsLit (HsLitLit str ty)
612 = ASSERT( maybeToBool maybe_ty )
613 returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
615 (maybe_ty, wrap_fn) = resultWrapper ty
616 Just rep_ty = maybe_ty
619 = mkIntegerLit (numerator r) `thenDs` \ num ->
620 mkIntegerLit (denominator r) `thenDs` \ denom ->
621 returnDs (mkConApp ratio_data_con [Type integer_ty, num, denom])
623 (ratio_data_con, integer_ty)
624 = case tcSplitTyConApp ty of
625 (tycon, [i_ty]) -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)
626 (head (tyConDataCons tycon), i_ty)