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, mkConsExpr, mkNilExpr )
29 import Match ( matchWrapper, matchSimply )
31 import CostCentre ( mkUserCC )
32 import FieldLabel ( FieldLabel )
33 import Id ( Id, idType, recordSelectorFieldLabel )
34 import DataCon ( DataCon, dataConId, dataConTyCon, dataConArgTys, dataConFieldLabels )
35 import PrelInfo ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID, addr2IntegerId )
36 import TyCon ( isNewTyCon )
37 import DataCon ( isExistentialDataCon )
38 import Literal ( Literal(..), inIntRange )
39 import Type ( splitFunTys, mkTyConApp,
40 splitAlgTyConApp, splitAlgTyConApp_maybe, splitTyConApp_maybe,
42 splitAppTy, isUnLiftedType, Type
44 import TysWiredIn ( tupleCon, unboxedTupleCon,
46 charDataCon, charTy, stringTy,
47 smallIntegerDataCon, isIntegerTy
49 import BasicTypes ( RecFlag(..) )
50 import Maybes ( maybeToBool )
51 import Unique ( Uniquable(..), ratioTyConKey )
52 import Util ( zipEqual, zipWithEqual )
55 import Ratio ( numerator, denominator )
59 %************************************************************************
63 %************************************************************************
65 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
66 and transforming it into one for the let-bindings enclosing the body.
68 This may seem a bit odd, but (source) let bindings can contain unboxed
73 This must be transformed to a case expression and, if the type has
74 more than one constructor, may fail.
77 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
82 dsLet (ThenBinds b1 b2) body
83 = dsLet b2 body `thenDs` \ body' ->
86 -- Special case for bindings which bind unlifted variables
87 -- Silently ignore INLINE pragmas...
88 dsLet (MonoBind (AbsBinds [] [] binder_triples inlines
89 (PatMonoBind pat grhss loc)) sigs is_rec) body
90 | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
91 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
93 dsGuarded grhss `thenDs` \ rhs ->
95 body' = foldr bind body binder_triples
96 bind (tyvars, g, l) body = ASSERT( null tyvars )
97 bindNonRec g (Var l) body
99 mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat))
100 `thenDs` \ error_expr ->
101 matchSimply rhs PatBindMatch pat body' error_expr
103 result_ty = exprType body
105 -- Ordinary case for bindings
106 dsLet (MonoBind binds sigs is_rec) body
107 = dsMonoBinds NoSccs binds [] `thenDs` \ prs ->
109 Recursive -> returnDs (Let (Rec prs) body)
110 NonRecursive -> returnDs (mkDsLets [NonRec b r | (b,r) <- prs] body)
113 %************************************************************************
115 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
117 %************************************************************************
120 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
122 dsExpr e@(HsVar var) = returnDs (Var var)
123 dsExpr e@(HsIPVar var) = returnDs (Var var)
126 %************************************************************************
128 \subsection[DsExpr-literals]{Literals}
130 %************************************************************************
132 We give int/float literals type @Integer@ and @Rational@, respectively.
133 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
136 ToDo: put in range checks for when converting ``@i@''
137 (or should that be in the typechecker?)
139 For numeric literals, we try to detect there use at a standard type
140 (@Int@, @Float@, etc.) are directly put in the right constructor.
141 [NB: down with the @App@ conversion.]
143 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
146 dsExpr (HsLitOut (HsString s) _)
148 = returnDs (mkNilExpr charTy)
152 the_char = mkConApp charDataCon [mkLit (MachChar (_HEAD_ s))]
153 the_nil = mkNilExpr charTy
154 the_cons = mkConsExpr charTy the_char the_nil
159 -- "_" => build (\ c n -> c 'c' n) -- LATER
161 dsExpr (HsLitOut (HsString str) _)
162 = returnDs (mkStringLitFS str)
164 dsExpr (HsLitOut (HsLitLit str) ty)
165 = ASSERT( maybeToBool maybe_ty )
166 returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
168 (maybe_ty, wrap_fn) = resultWrapper ty
169 Just rep_ty = maybe_ty
171 dsExpr (HsLitOut (HsInt i) ty)
172 = returnDs (mkIntegerLit i)
175 dsExpr (HsLitOut (HsFrac r) ty)
176 = returnDs (mkConApp ratio_data_con [Type integer_ty,
177 mkIntegerLit (numerator r),
178 mkIntegerLit (denominator r)])
180 (ratio_data_con, integer_ty)
181 = case (splitAlgTyConApp_maybe ty) of
182 Just (tycon, [i_ty], [con])
183 -> ASSERT(isIntegerTy i_ty && getUnique tycon == ratioTyConKey)
186 _ -> (panic "ratio_data_con", panic "integer_ty")
190 -- others where we know what to do:
192 dsExpr (HsLitOut (HsIntPrim i) _)
193 = returnDs (mkIntLit i)
195 dsExpr (HsLitOut (HsFloatPrim f) _)
196 = returnDs (mkLit (MachFloat f))
198 dsExpr (HsLitOut (HsDoublePrim d) _)
199 = returnDs (mkLit (MachDouble d))
200 -- ToDo: range checking needed!
202 dsExpr (HsLitOut (HsChar c) _)
203 = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
205 dsExpr (HsLitOut (HsCharPrim c) _)
206 = returnDs (mkLit (MachChar c))
208 dsExpr (HsLitOut (HsStringPrim s) _)
209 = returnDs (mkLit (MachStr s))
211 -- end of literals magic. --
213 dsExpr expr@(HsLam a_Match)
214 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
215 returnDs (mkLams binders matching_code)
217 dsExpr expr@(HsApp fun arg)
218 = dsExpr fun `thenDs` \ core_fun ->
219 dsExpr arg `thenDs` \ core_arg ->
220 returnDs (core_fun `App` core_arg)
224 Operator sections. At first it looks as if we can convert
233 But no! expr might be a redex, and we can lose laziness badly this
238 for example. So we convert instead to
240 let y = expr in \x -> op y x
242 If \tr{expr} is actually just a variable, say, then the simplifier
246 dsExpr (OpApp e1 op _ e2)
247 = dsExpr op `thenDs` \ core_op ->
248 -- for the type of y, we need the type of op's 2nd argument
249 dsExpr e1 `thenDs` \ x_core ->
250 dsExpr e2 `thenDs` \ y_core ->
251 returnDs (mkApps core_op [x_core, y_core])
253 dsExpr (SectionL expr op)
254 = dsExpr op `thenDs` \ core_op ->
255 -- for the type of y, we need the type of op's 2nd argument
257 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
259 dsExpr expr `thenDs` \ x_core ->
260 newSysLocalDs x_ty `thenDs` \ x_id ->
261 newSysLocalDs y_ty `thenDs` \ y_id ->
263 returnDs (bindNonRec x_id x_core $
264 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
266 -- dsExpr (SectionR op expr) -- \ x -> op x expr
267 dsExpr (SectionR op expr)
268 = dsExpr op `thenDs` \ core_op ->
269 -- for the type of x, we need the type of op's 2nd argument
271 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
273 dsExpr expr `thenDs` \ y_core ->
274 newSysLocalDs x_ty `thenDs` \ x_id ->
275 newSysLocalDs y_ty `thenDs` \ y_id ->
277 returnDs (bindNonRec y_id y_core $
278 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
280 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
281 = mapDs dsExpr args `thenDs` \ core_args ->
282 dsCCall lbl core_args may_gc is_asm result_ty
283 -- dsCCall does all the unboxification, etc.
285 dsExpr (HsSCC cc expr)
286 = dsExpr expr `thenDs` \ core_expr ->
287 getModuleDs `thenDs` \ mod_name ->
288 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
290 -- special case to handle unboxed tuple patterns.
292 dsExpr (HsCase discrim matches src_loc)
293 | all ubx_tuple_match matches
294 = putSrcLocDs src_loc $
295 dsExpr discrim `thenDs` \ core_discrim ->
296 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
297 case matching_code of
298 Case (Var x) bndr alts | x == discrim_var ->
299 returnDs (Case core_discrim bndr alts)
300 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
302 ubx_tuple_match (Match _ [TuplePat ps False{-unboxed-}] _ _) = True
303 ubx_tuple_match _ = False
305 dsExpr (HsCase discrim matches src_loc)
306 = putSrcLocDs src_loc $
307 dsExpr discrim `thenDs` \ core_discrim ->
308 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
309 returnDs (bindNonRec discrim_var core_discrim matching_code)
311 dsExpr (HsLet binds body)
312 = dsExpr body `thenDs` \ body' ->
315 dsExpr (HsWith expr binds)
316 = dsExpr expr `thenDs` \ expr' ->
317 foldlDs dsIPBind expr' binds
320 = dsExpr e `thenDs` \ e' ->
321 returnDs (Let (NonRec n e') body)
323 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
324 | maybeToBool maybe_list_comp
325 = -- Special case for list comprehensions
326 putSrcLocDs src_loc $
327 dsListComp stmts elt_ty
330 = putSrcLocDs src_loc $
331 dsDo do_or_lc stmts return_id then_id fail_id result_ty
334 = case (do_or_lc, splitTyConApp_maybe result_ty) of
335 (ListComp, Just (tycon, [elt_ty]))
339 -- We need the ListComp form to use deListComp (rather than the "do" form)
340 -- because the "return" in a do block is a call to "PrelBase.return", and
341 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
343 Just elt_ty = maybe_list_comp
345 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
346 = putSrcLocDs src_loc $
347 dsExpr guard_expr `thenDs` \ core_guard ->
348 dsExpr then_expr `thenDs` \ core_then ->
349 dsExpr else_expr `thenDs` \ core_else ->
350 returnDs (mkIfThenElse core_guard core_then core_else)
355 \underline{\bf Type lambda and application}
356 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
358 dsExpr (TyLam tyvars expr)
359 = dsExpr expr `thenDs` \ core_expr ->
360 returnDs (mkLams tyvars core_expr)
362 dsExpr (TyApp expr tys)
363 = dsExpr expr `thenDs` \ core_expr ->
364 returnDs (mkTyApps core_expr tys)
369 \underline{\bf Various data construction things}
370 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
372 dsExpr (ExplicitListOut ty xs)
375 list_ty = mkListTy ty
377 go [] = returnDs (mkNilExpr ty)
378 go (x:xs) = dsExpr x `thenDs` \ core_x ->
379 go xs `thenDs` \ core_xs ->
380 ASSERT( isNotUsgTy ty )
381 returnDs (mkConsExpr ty core_x core_xs)
383 dsExpr (ExplicitTuple expr_list boxed)
384 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
385 returnDs (mkConApp ((if boxed
387 else unboxedTupleCon) (length expr_list))
388 (map (Type . unUsgTy . exprType) core_exprs ++ core_exprs))
389 -- the above unUsgTy is *required* -- KSW 1999-04-07
391 dsExpr (ArithSeqOut expr (From from))
392 = dsExpr expr `thenDs` \ expr2 ->
393 dsExpr from `thenDs` \ from2 ->
394 returnDs (App expr2 from2)
396 dsExpr (ArithSeqOut expr (FromTo from two))
397 = dsExpr expr `thenDs` \ expr2 ->
398 dsExpr from `thenDs` \ from2 ->
399 dsExpr two `thenDs` \ two2 ->
400 returnDs (mkApps expr2 [from2, two2])
402 dsExpr (ArithSeqOut expr (FromThen from thn))
403 = dsExpr expr `thenDs` \ expr2 ->
404 dsExpr from `thenDs` \ from2 ->
405 dsExpr thn `thenDs` \ thn2 ->
406 returnDs (mkApps expr2 [from2, thn2])
408 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
409 = dsExpr expr `thenDs` \ expr2 ->
410 dsExpr from `thenDs` \ from2 ->
411 dsExpr thn `thenDs` \ thn2 ->
412 dsExpr two `thenDs` \ two2 ->
413 returnDs (mkApps expr2 [from2, thn2, two2])
417 \underline{\bf Record construction and update}
418 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
419 For record construction we do this (assuming T has three arguments)
423 let err = /\a -> recConErr a
424 T (recConErr t1 "M.lhs/230/op1")
426 (recConErr t1 "M.lhs/230/op3")
428 @recConErr@ then converts its arugment string into a proper message
429 before printing it as
431 M.lhs, line 230: missing field op1 was evaluated
434 We also handle @C{}@ as valid construction syntax for an unlabelled
435 constructor @C@, setting all of @C@'s fields to bottom.
438 dsExpr (RecordConOut data_con con_expr rbinds)
439 = dsExpr con_expr `thenDs` \ con_expr' ->
441 (arg_tys, _) = splitFunTys (exprType con_expr')
444 = case [rhs | (sel_id,rhs,_) <- rbinds,
445 lbl == recordSelectorFieldLabel sel_id] of
446 (rhs:rhss) -> ASSERT( null rhss )
448 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
449 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
451 labels = dataConFieldLabels data_con
455 then mapDs unlabelled_bottom arg_tys
456 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
457 `thenDs` \ con_args ->
459 returnDs (mkApps con_expr' con_args)
462 Record update is a little harder. Suppose we have the decl:
464 data T = T1 {op1, op2, op3 :: Int}
465 | T2 {op4, op2 :: Int}
468 Then we translate as follows:
474 T1 op1 _ op3 -> T1 op1 op2 op3
475 T2 op4 _ -> T2 op4 op2
476 other -> recUpdError "M.lhs/230"
478 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
479 RHSs, and do not generate a Core constructor application directly, because the constructor
480 might do some argument-evaluation first; and may have to throw away some
484 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
485 = getSrcLocDs `thenDs` \ src_loc ->
486 dsExpr record_expr `thenDs` \ record_expr' ->
488 -- Desugar the rbinds, and generate let-bindings if
489 -- necessary so that we don't lose sharing
492 record_in_ty = exprType record_expr'
493 (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
494 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
495 cons_to_upd = filter has_all_fields cons
497 mk_val_arg field old_arg_id
498 = case [rhs | (sel_id, rhs, _) <- rbinds,
499 field == recordSelectorFieldLabel sel_id] of
500 (rhs:rest) -> ASSERT(null rest) rhs
501 [] -> HsVar old_arg_id
504 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
505 -- This call to dataConArgTys won't work for existentials
507 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
508 (dataConFieldLabels con) arg_ids
509 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConId con))
514 returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
519 -- Record stuff doesn't work for existentials
520 ASSERT( all (not . isExistentialDataCon) cons )
522 -- It's important to generate the match with matchWrapper,
523 -- and the right hand sides with applications of the wrapper Id
524 -- so that everything works when we are doing fancy unboxing on the
525 -- constructor aguments.
526 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
527 matchWrapper RecUpdMatch alts "record update" `thenDs` \ ([discrim_var], matching_code) ->
529 returnDs (bindNonRec discrim_var record_expr' matching_code)
532 has_all_fields :: DataCon -> Bool
533 has_all_fields con_id
536 con_fields = dataConFieldLabels con_id
537 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
542 \underline{\bf Dictionary lambda and application}
543 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
544 @DictLam@ and @DictApp@ turn into the regular old things.
545 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
546 complicated; reminiscent of fully-applied constructors.
548 dsExpr (DictLam dictvars expr)
549 = dsExpr expr `thenDs` \ core_expr ->
550 returnDs (mkLams dictvars core_expr)
554 dsExpr (DictApp expr dicts) -- becomes a curried application
555 = dsExpr expr `thenDs` \ core_expr ->
556 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
562 -- HsSyn constructs that just shouldn't be here:
563 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
564 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
565 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
566 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
571 %--------------------------------------------------------------------
573 Basically does the translation given in the Haskell~1.3 report:
578 -> Id -- id for: return m
579 -> Id -- id for: (>>=) m
580 -> Id -- id for: fail m
581 -> Type -- Element type; the whole expression has type (m t)
584 dsDo do_or_lc stmts return_id then_id fail_id result_ty
586 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
589 = dsExpr expr `thenDs` \ expr2 ->
590 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
592 go (GuardStmt expr locn : stmts)
593 = do_expr expr locn `thenDs` \ expr2 ->
594 go stmts `thenDs` \ rest ->
595 let msg = ASSERT( isNotUsgTy b_ty )
596 "Pattern match failure in do expression, " ++ showSDoc (ppr locn) in
597 returnDs (mkIfThenElse expr2
599 (App (App (Var fail_id)
603 go (ExprStmt expr locn : stmts)
604 = do_expr expr locn `thenDs` \ expr2 ->
606 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
611 go stmts `thenDs` \ rest ->
612 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
613 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
614 Lam ignored_result_id rest])
616 go (LetStmt binds : stmts )
617 = go stmts `thenDs` \ rest ->
620 go (BindStmt pat expr locn : stmts)
622 dsExpr expr `thenDs` \ expr2 ->
624 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
625 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
626 (HsLitOut (HsString (_PK_ msg)) stringTy)
627 msg = ASSERT2( isNotUsgTy a_ty, ppr a_ty )
628 ASSERT2( isNotUsgTy b_ty, ppr b_ty )
629 "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
630 main_match = mkSimpleMatch [pat]
631 (HsDoOut do_or_lc stmts return_id then_id
632 fail_id result_ty locn)
633 (Just result_ty) locn
635 | failureFreePat pat = [main_match]
638 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
641 matchWrapper DoBindMatch the_matches match_msg
642 `thenDs` \ (binders, matching_code) ->
643 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
644 mkLams binders matching_code])
649 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
651 match_msg = case do_or_lc of
652 DoStmt -> "`do' statement"
653 ListComp -> "comprehension"
657 var_pat (WildPat _) = True
658 var_pat (VarPat _) = True
663 mkIntegerLit :: Integer -> CoreExpr
665 | inIntRange i -- Small enough, so start from an Int
666 = mkConApp smallIntegerDataCon [mkIntLit i]
668 | otherwise -- Big, so start from a string
669 = App (Var addr2IntegerId) (Lit (MachStr (_PK_ (show i))))