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(..), StmtCtxt(..), Match(..), HsBinds(..), MonoBinds(..),
17 import TcHsSyn ( TypecheckedHsExpr, TypecheckedHsBinds,
21 import CoreUtils ( exprType, mkIfThenElse, bindNonRec )
24 import DsBinds ( dsMonoBinds, AutoScc(..) )
25 import DsGRHSs ( dsGuarded )
26 import DsCCall ( dsCCall, resultWrapper )
27 import DsListComp ( dsListComp )
28 import DsUtils ( mkErrorAppDs, mkDsLets, mkStringLit, mkStringLitFS,
31 import Match ( matchWrapper, matchSimply )
33 import CostCentre ( mkUserCC )
34 import Id ( Id, idType, recordSelectorFieldLabel )
35 import PrelInfo ( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
36 import DataCon ( DataCon, dataConWrapId, dataConTyCon, dataConArgTys, dataConFieldLabels )
37 import DataCon ( isExistentialDataCon )
38 import Literal ( Literal(..), inIntRange )
39 import Type ( splitFunTys,
40 splitAlgTyConApp, splitAlgTyConApp_maybe, splitTyConApp_maybe,
42 splitAppTy, isUnLiftedType, Type
44 import TysWiredIn ( tupleCon, listTyCon,
45 charDataCon, charTy, stringTy,
46 smallIntegerDataCon, isIntegerTy
48 import BasicTypes ( RecFlag(..), Boxity(..) )
49 import Maybes ( maybeToBool )
50 import Unique ( hasKey, ratioTyConKey, addr2IntegerIdKey )
51 import Util ( zipEqual, zipWithEqual )
54 import Ratio ( numerator, denominator )
58 %************************************************************************
62 %************************************************************************
64 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
65 and transforming it into one for the let-bindings enclosing the body.
67 This may seem a bit odd, but (source) let bindings can contain unboxed
72 This must be transformed to a case expression and, if the type has
73 more than one constructor, may fail.
76 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
81 dsLet (ThenBinds b1 b2) body
82 = dsLet b2 body `thenDs` \ body' ->
85 -- Special case for bindings which bind unlifted variables
86 -- Silently ignore INLINE pragmas...
87 dsLet (MonoBind (AbsBinds [] [] binder_triples inlines
88 (PatMonoBind pat grhss loc)) sigs is_rec) body
89 | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
90 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
92 dsGuarded grhss `thenDs` \ rhs ->
94 body' = foldr bind body binder_triples
95 bind (tyvars, g, l) body = ASSERT( null tyvars )
96 bindNonRec g (Var l) body
98 mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat))
99 `thenDs` \ error_expr ->
100 matchSimply rhs PatBindMatch pat body' error_expr
102 result_ty = exprType body
104 -- Ordinary case for bindings
105 dsLet (MonoBind binds sigs is_rec) body
106 = dsMonoBinds NoSccs binds [] `thenDs` \ prs ->
108 Recursive -> returnDs (Let (Rec prs) body)
109 NonRecursive -> returnDs (mkDsLets [NonRec b r | (b,r) <- prs] body)
112 %************************************************************************
114 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
116 %************************************************************************
119 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
121 dsExpr e@(HsVar var) = returnDs (Var var)
122 dsExpr e@(HsIPVar var) = returnDs (Var var)
125 %************************************************************************
127 \subsection[DsExpr-literals]{Literals}
129 %************************************************************************
131 We give int/float literals type @Integer@ and @Rational@, respectively.
132 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
135 ToDo: put in range checks for when converting ``@i@''
136 (or should that be in the typechecker?)
138 For numeric literals, we try to detect there use at a standard type
139 (@Int@, @Float@, etc.) are directly put in the right constructor.
140 [NB: down with the @App@ conversion.]
142 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
145 dsExpr (HsLitOut (HsString s) _)
147 = returnDs (mkNilExpr charTy)
151 the_char = mkConApp charDataCon [mkLit (MachChar (_HEAD_ s))]
152 the_nil = mkNilExpr charTy
153 the_cons = mkConsExpr charTy the_char the_nil
158 -- "_" => build (\ c n -> c 'c' n) -- LATER
160 dsExpr (HsLitOut (HsString str) _)
163 dsExpr (HsLitOut (HsLitLit str) ty)
164 = ASSERT( maybeToBool maybe_ty )
165 returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
167 (maybe_ty, wrap_fn) = resultWrapper ty
168 Just rep_ty = maybe_ty
170 dsExpr (HsLitOut (HsInt i) ty)
174 dsExpr (HsLitOut (HsFrac r) ty)
175 = mkIntegerLit (numerator r) `thenDs` \ num ->
176 mkIntegerLit (denominator r) `thenDs` \ denom ->
177 returnDs (mkConApp ratio_data_con [Type integer_ty, num, denom])
179 (ratio_data_con, integer_ty)
180 = case (splitAlgTyConApp_maybe ty) of
181 Just (tycon, [i_ty], [con])
182 -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)
185 _ -> (panic "ratio_data_con", panic "integer_ty")
188 -- others where we know what to do:
190 dsExpr (HsLitOut (HsIntPrim i) _)
191 = returnDs (mkIntLit i)
193 dsExpr (HsLitOut (HsFloatPrim f) _)
194 = returnDs (mkLit (MachFloat f))
196 dsExpr (HsLitOut (HsDoublePrim d) _)
197 = returnDs (mkLit (MachDouble d))
198 -- ToDo: range checking needed!
200 dsExpr (HsLitOut (HsChar c) _)
201 = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
203 dsExpr (HsLitOut (HsCharPrim c) _)
204 = returnDs (mkLit (MachChar c))
206 dsExpr (HsLitOut (HsStringPrim s) _)
207 = returnDs (mkLit (MachStr s))
209 -- end of literals magic. --
211 dsExpr expr@(HsLam a_Match)
212 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
213 returnDs (mkLams binders matching_code)
215 dsExpr expr@(HsApp fun arg)
216 = dsExpr fun `thenDs` \ core_fun ->
217 dsExpr arg `thenDs` \ core_arg ->
218 returnDs (core_fun `App` core_arg)
222 Operator sections. At first it looks as if we can convert
231 But no! expr might be a redex, and we can lose laziness badly this
236 for example. So we convert instead to
238 let y = expr in \x -> op y x
240 If \tr{expr} is actually just a variable, say, then the simplifier
244 dsExpr (OpApp e1 op _ e2)
245 = dsExpr op `thenDs` \ core_op ->
246 -- for the type of y, we need the type of op's 2nd argument
247 dsExpr e1 `thenDs` \ x_core ->
248 dsExpr e2 `thenDs` \ y_core ->
249 returnDs (mkApps core_op [x_core, y_core])
251 dsExpr (SectionL expr op)
252 = dsExpr op `thenDs` \ core_op ->
253 -- for the type of y, we need the type of op's 2nd argument
255 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
257 dsExpr expr `thenDs` \ x_core ->
258 newSysLocalDs x_ty `thenDs` \ x_id ->
259 newSysLocalDs y_ty `thenDs` \ y_id ->
261 returnDs (bindNonRec x_id x_core $
262 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
264 -- dsExpr (SectionR op expr) -- \ x -> op x expr
265 dsExpr (SectionR op expr)
266 = dsExpr op `thenDs` \ core_op ->
267 -- for the type of x, we need the type of op's 2nd argument
269 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
271 dsExpr expr `thenDs` \ y_core ->
272 newSysLocalDs x_ty `thenDs` \ x_id ->
273 newSysLocalDs y_ty `thenDs` \ y_id ->
275 returnDs (bindNonRec y_id y_core $
276 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
278 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
279 = mapDs dsExpr args `thenDs` \ core_args ->
280 dsCCall lbl core_args may_gc is_asm result_ty
281 -- dsCCall does all the unboxification, etc.
283 dsExpr (HsSCC cc expr)
284 = dsExpr expr `thenDs` \ core_expr ->
285 getModuleDs `thenDs` \ mod_name ->
286 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
288 -- special case to handle unboxed tuple patterns.
290 dsExpr (HsCase discrim matches src_loc)
291 | all ubx_tuple_match matches
292 = putSrcLocDs src_loc $
293 dsExpr discrim `thenDs` \ core_discrim ->
294 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
295 case matching_code of
296 Case (Var x) bndr alts | x == discrim_var ->
297 returnDs (Case core_discrim bndr alts)
298 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
300 ubx_tuple_match (Match _ [TuplePat ps Unboxed] _ _) = True
301 ubx_tuple_match _ = False
303 dsExpr (HsCase discrim matches src_loc)
304 = putSrcLocDs src_loc $
305 dsExpr discrim `thenDs` \ core_discrim ->
306 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
307 returnDs (bindNonRec discrim_var core_discrim matching_code)
309 dsExpr (HsLet binds body)
310 = dsExpr body `thenDs` \ body' ->
313 dsExpr (HsWith expr binds)
314 = dsExpr expr `thenDs` \ expr' ->
315 foldlDs dsIPBind expr' binds
318 = dsExpr e `thenDs` \ e' ->
319 returnDs (Let (NonRec n e') body)
321 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
322 | maybeToBool maybe_list_comp
323 = -- Special case for list comprehensions
324 putSrcLocDs src_loc $
325 dsListComp stmts elt_ty
328 = putSrcLocDs src_loc $
329 dsDo do_or_lc stmts return_id then_id fail_id result_ty
332 = case (do_or_lc, splitTyConApp_maybe result_ty) of
333 (ListComp, Just (tycon, [elt_ty]))
337 -- We need the ListComp form to use deListComp (rather than the "do" form)
338 -- because the "return" in a do block is a call to "PrelBase.return", and
339 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
341 Just elt_ty = maybe_list_comp
343 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
344 = putSrcLocDs src_loc $
345 dsExpr guard_expr `thenDs` \ core_guard ->
346 dsExpr then_expr `thenDs` \ core_then ->
347 dsExpr else_expr `thenDs` \ core_else ->
348 returnDs (mkIfThenElse core_guard core_then core_else)
353 \underline{\bf Type lambda and application}
354 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
356 dsExpr (TyLam tyvars expr)
357 = dsExpr expr `thenDs` \ core_expr ->
358 returnDs (mkLams tyvars core_expr)
360 dsExpr (TyApp expr tys)
361 = dsExpr expr `thenDs` \ core_expr ->
362 returnDs (mkTyApps core_expr tys)
367 \underline{\bf Various data construction things}
368 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
370 dsExpr (ExplicitListOut ty xs)
373 go [] = returnDs (mkNilExpr ty)
374 go (x:xs) = dsExpr x `thenDs` \ core_x ->
375 go xs `thenDs` \ core_xs ->
376 ASSERT( isNotUsgTy ty )
377 returnDs (mkConsExpr ty core_x core_xs)
379 dsExpr (ExplicitTuple expr_list boxity)
380 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
381 returnDs (mkConApp (tupleCon boxity (length expr_list))
382 (map (Type . unUsgTy . exprType) core_exprs ++ core_exprs))
383 -- the above unUsgTy is *required* -- KSW 1999-04-07
385 dsExpr (ArithSeqOut expr (From from))
386 = dsExpr expr `thenDs` \ expr2 ->
387 dsExpr from `thenDs` \ from2 ->
388 returnDs (App expr2 from2)
390 dsExpr (ArithSeqOut expr (FromTo from two))
391 = dsExpr expr `thenDs` \ expr2 ->
392 dsExpr from `thenDs` \ from2 ->
393 dsExpr two `thenDs` \ two2 ->
394 returnDs (mkApps expr2 [from2, two2])
396 dsExpr (ArithSeqOut expr (FromThen from thn))
397 = dsExpr expr `thenDs` \ expr2 ->
398 dsExpr from `thenDs` \ from2 ->
399 dsExpr thn `thenDs` \ thn2 ->
400 returnDs (mkApps expr2 [from2, thn2])
402 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
403 = dsExpr expr `thenDs` \ expr2 ->
404 dsExpr from `thenDs` \ from2 ->
405 dsExpr thn `thenDs` \ thn2 ->
406 dsExpr two `thenDs` \ two2 ->
407 returnDs (mkApps expr2 [from2, thn2, two2])
411 \underline{\bf Record construction and update}
412 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
413 For record construction we do this (assuming T has three arguments)
417 let err = /\a -> recConErr a
418 T (recConErr t1 "M.lhs/230/op1")
420 (recConErr t1 "M.lhs/230/op3")
422 @recConErr@ then converts its arugment string into a proper message
423 before printing it as
425 M.lhs, line 230: missing field op1 was evaluated
428 We also handle @C{}@ as valid construction syntax for an unlabelled
429 constructor @C@, setting all of @C@'s fields to bottom.
432 dsExpr (RecordConOut data_con con_expr rbinds)
433 = dsExpr con_expr `thenDs` \ con_expr' ->
435 (arg_tys, _) = splitFunTys (exprType con_expr')
438 = case [rhs | (sel_id,rhs,_) <- rbinds,
439 lbl == recordSelectorFieldLabel sel_id] of
440 (rhs:rhss) -> ASSERT( null rhss )
442 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
443 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
445 labels = dataConFieldLabels data_con
449 then mapDs unlabelled_bottom arg_tys
450 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
451 `thenDs` \ con_args ->
453 returnDs (mkApps con_expr' con_args)
456 Record update is a little harder. Suppose we have the decl:
458 data T = T1 {op1, op2, op3 :: Int}
459 | T2 {op4, op2 :: Int}
462 Then we translate as follows:
468 T1 op1 _ op3 -> T1 op1 op2 op3
469 T2 op4 _ -> T2 op4 op2
470 other -> recUpdError "M.lhs/230"
472 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
473 RHSs, and do not generate a Core constructor application directly, because the constructor
474 might do some argument-evaluation first; and may have to throw away some
478 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
479 = getSrcLocDs `thenDs` \ src_loc ->
480 dsExpr record_expr `thenDs` \ record_expr' ->
482 -- Desugar the rbinds, and generate let-bindings if
483 -- necessary so that we don't lose sharing
486 record_in_ty = exprType record_expr'
487 (_, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
488 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
489 cons_to_upd = filter has_all_fields cons
491 mk_val_arg field old_arg_id
492 = case [rhs | (sel_id, rhs, _) <- rbinds,
493 field == recordSelectorFieldLabel sel_id] of
494 (rhs:rest) -> ASSERT(null rest) rhs
495 [] -> HsVar old_arg_id
498 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
499 -- This call to dataConArgTys won't work for existentials
501 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
502 (dataConFieldLabels con) arg_ids
503 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConWrapId con))
508 returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
513 -- Record stuff doesn't work for existentials
514 ASSERT( all (not . isExistentialDataCon) cons )
516 -- It's important to generate the match with matchWrapper,
517 -- and the right hand sides with applications of the wrapper Id
518 -- so that everything works when we are doing fancy unboxing on the
519 -- constructor aguments.
520 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
521 matchWrapper RecUpdMatch alts "record update" `thenDs` \ ([discrim_var], matching_code) ->
523 returnDs (bindNonRec discrim_var record_expr' matching_code)
526 has_all_fields :: DataCon -> Bool
527 has_all_fields con_id
530 con_fields = dataConFieldLabels con_id
531 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
536 \underline{\bf Dictionary lambda and application}
537 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
538 @DictLam@ and @DictApp@ turn into the regular old things.
539 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
540 complicated; reminiscent of fully-applied constructors.
542 dsExpr (DictLam dictvars expr)
543 = dsExpr expr `thenDs` \ core_expr ->
544 returnDs (mkLams dictvars core_expr)
548 dsExpr (DictApp expr dicts) -- becomes a curried application
549 = dsExpr expr `thenDs` \ core_expr ->
550 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
556 -- HsSyn constructs that just shouldn't be here:
557 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
558 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
559 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
560 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
565 %--------------------------------------------------------------------
567 Basically does the translation given in the Haskell~1.3 report:
572 -> Id -- id for: return m
573 -> Id -- id for: (>>=) m
574 -> Id -- id for: fail m
575 -> Type -- Element type; the whole expression has type (m t)
578 dsDo do_or_lc stmts return_id then_id fail_id result_ty
580 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
583 = dsExpr expr `thenDs` \ expr2 ->
584 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
586 go (GuardStmt expr locn : stmts)
587 = do_expr expr locn `thenDs` \ expr2 ->
588 go stmts `thenDs` \ rest ->
589 let msg = ASSERT( isNotUsgTy b_ty )
590 "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
592 mkStringLit msg `thenDs` \ core_msg ->
593 returnDs (mkIfThenElse expr2
595 (App (App (Var fail_id)
599 go (ExprStmt expr locn : stmts)
600 = do_expr expr locn `thenDs` \ expr2 ->
602 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
607 go stmts `thenDs` \ rest ->
608 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
609 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
610 Lam ignored_result_id rest])
612 go (LetStmt binds : stmts )
613 = go stmts `thenDs` \ rest ->
616 go (BindStmt pat expr locn : stmts)
618 dsExpr expr `thenDs` \ expr2 ->
620 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
621 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
622 (HsLitOut (HsString (_PK_ msg)) stringTy)
623 msg = ASSERT2( isNotUsgTy a_ty, ppr a_ty )
624 ASSERT2( isNotUsgTy b_ty, ppr b_ty )
625 "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
626 main_match = mkSimpleMatch [pat]
627 (HsDoOut do_or_lc stmts return_id then_id
628 fail_id result_ty locn)
629 (Just result_ty) locn
631 | failureFreePat pat = [main_match]
634 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
637 matchWrapper DoBindMatch the_matches match_msg
638 `thenDs` \ (binders, matching_code) ->
639 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
640 mkLams binders matching_code])
645 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
647 match_msg = case do_or_lc of
648 DoStmt -> "`do' statement"
649 ListComp -> "comprehension"
653 var_pat (WildPat _) = True
654 var_pat (VarPat _) = True
659 mkIntegerLit :: Integer -> DsM CoreExpr
661 | inIntRange i -- Small enough, so start from an Int
662 = returnDs (mkConApp smallIntegerDataCon [mkIntLit i])
664 | otherwise -- Big, so start from a string
665 = dsLookupGlobalValue addr2IntegerIdKey `thenDs` \ addr2IntegerId ->
666 returnDs (App (Var addr2IntegerId) (Lit (MachStr (_PK_ (show i)))))