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,
23 import CoreUtils ( exprType, mkIfThenElse, bindNonRec )
26 import DsBinds ( dsMonoBinds, AutoScc(..) )
27 import DsGRHSs ( dsGuarded )
28 import DsCCall ( dsCCall )
29 import DsListComp ( dsListComp )
30 import DsUtils ( mkErrorAppDs, mkDsLets, mkConsExpr, mkNilExpr )
31 import Match ( matchWrapper, matchSimply )
33 import CostCentre ( mkUserCC )
34 import FieldLabel ( FieldLabel )
35 import Id ( Id, idType, recordSelectorFieldLabel )
36 import DataCon ( DataCon, dataConId, dataConTyCon, dataConArgTys, dataConFieldLabels )
37 import PrelInfo ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID, addr2IntegerId )
38 import TyCon ( isNewTyCon )
39 import DataCon ( isExistentialDataCon )
40 import Literal ( Literal(..), inIntRange )
41 import Type ( splitFunTys, mkTyConApp,
42 splitAlgTyConApp, splitAlgTyConApp_maybe, splitTyConApp_maybe,
44 splitAppTy, isUnLiftedType, Type
46 import PprType ( {- instance Outputable Type -} )
47 import TysWiredIn ( tupleCon, unboxedTupleCon,
49 charDataCon, charTy, stringTy,
50 smallIntegerDataCon, isIntegerTy
52 import BasicTypes ( RecFlag(..) )
53 import Maybes ( maybeToBool )
54 import Unique ( Uniquable(..), ratioTyConKey )
55 import Util ( zipEqual, zipWithEqual )
58 import Ratio ( numerator, denominator )
62 %************************************************************************
66 %************************************************************************
68 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
69 and transforming it into one for the let-bindings enclosing the body.
71 This may seem a bit odd, but (source) let bindings can contain unboxed
76 This must be transformed to a case expression and, if the type has
77 more than one constructor, may fail.
80 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
85 dsLet (ThenBinds b1 b2) body
86 = dsLet b2 body `thenDs` \ body' ->
89 -- Special case for bindings which bind unlifted variables
90 -- Silently ignore INLINE pragmas...
91 dsLet (MonoBind (AbsBinds [] [] binder_triples inlines
92 (PatMonoBind pat grhss loc)) sigs is_rec) body
93 | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
94 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
96 dsGuarded grhss `thenDs` \ rhs ->
98 body' = foldr bind body binder_triples
99 bind (tyvars, g, l) body = ASSERT( null tyvars )
100 bindNonRec g (Var l) body
102 mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat))
103 `thenDs` \ error_expr ->
104 matchSimply rhs PatBindMatch pat body' error_expr
106 result_ty = exprType body
108 -- Ordinary case for bindings
109 dsLet (MonoBind binds sigs is_rec) body
110 = dsMonoBinds NoSccs binds [] `thenDs` \ prs ->
112 Recursive -> returnDs (Let (Rec prs) body)
113 NonRecursive -> returnDs (mkDsLets [NonRec b r | (b,r) <- prs] body)
116 %************************************************************************
118 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
120 %************************************************************************
123 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
125 dsExpr e@(HsVar var) = returnDs (Var var)
126 dsExpr e@(HsIPVar var) = returnDs (Var var)
129 %************************************************************************
131 \subsection[DsExpr-literals]{Literals}
133 %************************************************************************
135 We give int/float literals type @Integer@ and @Rational@, respectively.
136 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
139 ToDo: put in range checks for when converting ``@i@''
140 (or should that be in the typechecker?)
142 For numeric literals, we try to detect there use at a standard type
143 (@Int@, @Float@, etc.) are directly put in the right constructor.
144 [NB: down with the @App@ conversion.]
146 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
149 dsExpr (HsLitOut (HsString s) _)
151 = returnDs (mkNilExpr charTy)
155 the_char = mkConApp charDataCon [mkLit (MachChar (_HEAD_ s))]
156 the_nil = mkNilExpr charTy
157 the_cons = mkConsExpr charTy the_char the_nil
162 -- "_" => build (\ c n -> c 'c' n) -- LATER
164 dsExpr (HsLitOut (HsString str) _)
165 = returnDs (mkStringLitFS str)
167 dsExpr (HsLitOut (HsLitLit str) ty)
169 = returnDs (mkLit (MachLitLit str ty))
171 = case (maybeBoxedPrimType ty) of
172 Just (boxing_data_con, prim_ty) ->
173 returnDs ( mkConApp boxing_data_con [mkLit (MachLitLit str prim_ty)] )
177 [ hcat [ text "Cannot see data constructor of ``literal-literal''s type: "
178 , text "value:", quotes (quotes (ptext str))
179 , text "; type: ", ppr ty
181 , text "Try compiling with -fno-prune-tydecls."
186 = case (maybeBoxedPrimType ty) of
187 Just (boxing_data_con, prim_ty) -> (boxing_data_con, prim_ty)
189 -> pprPanic "ERROR: ``literal-literal'' not a single-constructor type: "
190 (hcat [ptext str, text "; type: ", ppr ty])
192 dsExpr (HsLitOut (HsInt i) ty)
193 = returnDs (mkIntegerLit i)
196 dsExpr (HsLitOut (HsFrac r) ty)
197 = returnDs (mkConApp ratio_data_con [Type integer_ty,
198 mkIntegerLit (numerator r),
199 mkIntegerLit (denominator r)])
201 (ratio_data_con, integer_ty)
202 = case (splitAlgTyConApp_maybe ty) of
203 Just (tycon, [i_ty], [con])
204 -> ASSERT(isIntegerTy i_ty && getUnique tycon == ratioTyConKey)
207 _ -> (panic "ratio_data_con", panic "integer_ty")
211 -- others where we know what to do:
213 dsExpr (HsLitOut (HsIntPrim i) _)
214 = returnDs (mkIntLit i)
216 dsExpr (HsLitOut (HsFloatPrim f) _)
217 = returnDs (mkLit (MachFloat f))
219 dsExpr (HsLitOut (HsDoublePrim d) _)
220 = returnDs (mkLit (MachDouble d))
221 -- ToDo: range checking needed!
223 dsExpr (HsLitOut (HsChar c) _)
224 = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
226 dsExpr (HsLitOut (HsCharPrim c) _)
227 = returnDs (mkLit (MachChar c))
229 dsExpr (HsLitOut (HsStringPrim s) _)
230 = returnDs (mkLit (MachStr s))
232 -- end of literals magic. --
234 dsExpr expr@(HsLam a_Match)
235 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
236 returnDs (mkLams binders matching_code)
238 dsExpr expr@(HsApp fun arg)
239 = dsExpr fun `thenDs` \ core_fun ->
240 dsExpr arg `thenDs` \ core_arg ->
241 returnDs (core_fun `App` core_arg)
245 Operator sections. At first it looks as if we can convert
254 But no! expr might be a redex, and we can lose laziness badly this
259 for example. So we convert instead to
261 let y = expr in \x -> op y x
263 If \tr{expr} is actually just a variable, say, then the simplifier
267 dsExpr (OpApp e1 op _ e2)
268 = dsExpr op `thenDs` \ core_op ->
269 -- for the type of y, we need the type of op's 2nd argument
270 dsExpr e1 `thenDs` \ x_core ->
271 dsExpr e2 `thenDs` \ y_core ->
272 returnDs (mkApps core_op [x_core, y_core])
274 dsExpr (SectionL expr op)
275 = dsExpr op `thenDs` \ core_op ->
276 -- for the type of y, we need the type of op's 2nd argument
278 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
280 dsExpr expr `thenDs` \ x_core ->
281 newSysLocalDs x_ty `thenDs` \ x_id ->
282 newSysLocalDs y_ty `thenDs` \ y_id ->
284 returnDs (bindNonRec x_id x_core $
285 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
287 -- dsExpr (SectionR op expr) -- \ x -> op x expr
288 dsExpr (SectionR op expr)
289 = dsExpr op `thenDs` \ core_op ->
290 -- for the type of x, we need the type of op's 2nd argument
292 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
294 dsExpr expr `thenDs` \ y_core ->
295 newSysLocalDs x_ty `thenDs` \ x_id ->
296 newSysLocalDs y_ty `thenDs` \ y_id ->
298 returnDs (bindNonRec y_id y_core $
299 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
301 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
302 = mapDs dsExpr args `thenDs` \ core_args ->
303 dsCCall lbl core_args may_gc is_asm result_ty
304 -- dsCCall does all the unboxification, etc.
306 dsExpr (HsSCC cc expr)
307 = dsExpr expr `thenDs` \ core_expr ->
308 getModuleDs `thenDs` \ mod_name ->
309 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
311 -- special case to handle unboxed tuple patterns.
313 dsExpr (HsCase discrim matches src_loc)
314 | all ubx_tuple_match matches
315 = putSrcLocDs src_loc $
316 dsExpr discrim `thenDs` \ core_discrim ->
317 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
318 case matching_code of
319 Case (Var x) bndr alts | x == discrim_var ->
320 returnDs (Case core_discrim bndr alts)
321 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
323 ubx_tuple_match (Match _ [TuplePat ps False{-unboxed-}] _ _) = True
324 ubx_tuple_match _ = False
326 dsExpr (HsCase discrim matches src_loc)
327 = putSrcLocDs src_loc $
328 dsExpr discrim `thenDs` \ core_discrim ->
329 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
330 returnDs (bindNonRec discrim_var core_discrim matching_code)
332 dsExpr (HsLet binds body)
333 = dsExpr body `thenDs` \ body' ->
336 dsExpr (HsWith expr binds)
337 = dsExpr expr `thenDs` \ expr' ->
338 foldlDs dsIPBind expr' binds
341 = dsExpr e `thenDs` \ e' ->
342 returnDs (Let (NonRec n e') body)
344 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
345 | maybeToBool maybe_list_comp
346 = -- Special case for list comprehensions
347 putSrcLocDs src_loc $
348 dsListComp stmts elt_ty
351 = putSrcLocDs src_loc $
352 dsDo do_or_lc stmts return_id then_id fail_id result_ty
355 = case (do_or_lc, splitTyConApp_maybe result_ty) of
356 (ListComp, Just (tycon, [elt_ty]))
360 -- We need the ListComp form to use deListComp (rather than the "do" form)
361 -- because the "return" in a do block is a call to "PrelBase.return", and
362 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
364 Just elt_ty = maybe_list_comp
366 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
367 = putSrcLocDs src_loc $
368 dsExpr guard_expr `thenDs` \ core_guard ->
369 dsExpr then_expr `thenDs` \ core_then ->
370 dsExpr else_expr `thenDs` \ core_else ->
371 returnDs (mkIfThenElse core_guard core_then core_else)
376 \underline{\bf Type lambda and application}
377 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
379 dsExpr (TyLam tyvars expr)
380 = dsExpr expr `thenDs` \ core_expr ->
381 returnDs (mkLams tyvars core_expr)
383 dsExpr (TyApp expr tys)
384 = dsExpr expr `thenDs` \ core_expr ->
385 returnDs (mkTyApps core_expr tys)
390 \underline{\bf Various data construction things}
391 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
393 dsExpr (ExplicitListOut ty xs)
396 list_ty = mkListTy ty
398 go [] = returnDs (mkNilExpr ty)
399 go (x:xs) = dsExpr x `thenDs` \ core_x ->
400 go xs `thenDs` \ core_xs ->
401 ASSERT( isNotUsgTy ty )
402 returnDs (mkConsExpr ty core_x core_xs)
404 dsExpr (ExplicitTuple expr_list boxed)
405 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
406 returnDs (mkConApp ((if boxed
408 else unboxedTupleCon) (length expr_list))
409 (map (Type . unUsgTy . exprType) core_exprs ++ core_exprs))
410 -- the above unUsgTy is *required* -- KSW 1999-04-07
412 dsExpr (ArithSeqOut expr (From from))
413 = dsExpr expr `thenDs` \ expr2 ->
414 dsExpr from `thenDs` \ from2 ->
415 returnDs (App expr2 from2)
417 dsExpr (ArithSeqOut expr (FromTo from two))
418 = dsExpr expr `thenDs` \ expr2 ->
419 dsExpr from `thenDs` \ from2 ->
420 dsExpr two `thenDs` \ two2 ->
421 returnDs (mkApps expr2 [from2, two2])
423 dsExpr (ArithSeqOut expr (FromThen from thn))
424 = dsExpr expr `thenDs` \ expr2 ->
425 dsExpr from `thenDs` \ from2 ->
426 dsExpr thn `thenDs` \ thn2 ->
427 returnDs (mkApps expr2 [from2, thn2])
429 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
430 = dsExpr expr `thenDs` \ expr2 ->
431 dsExpr from `thenDs` \ from2 ->
432 dsExpr thn `thenDs` \ thn2 ->
433 dsExpr two `thenDs` \ two2 ->
434 returnDs (mkApps expr2 [from2, thn2, two2])
438 \underline{\bf Record construction and update}
439 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
440 For record construction we do this (assuming T has three arguments)
444 let err = /\a -> recConErr a
445 T (recConErr t1 "M.lhs/230/op1")
447 (recConErr t1 "M.lhs/230/op3")
449 @recConErr@ then converts its arugment string into a proper message
450 before printing it as
452 M.lhs, line 230: missing field op1 was evaluated
455 We also handle @C{}@ as valid construction syntax for an unlabelled
456 constructor @C@, setting all of @C@'s fields to bottom.
459 dsExpr (RecordConOut data_con con_expr rbinds)
460 = dsExpr con_expr `thenDs` \ con_expr' ->
462 (arg_tys, _) = splitFunTys (exprType con_expr')
465 = case [rhs | (sel_id,rhs,_) <- rbinds,
466 lbl == recordSelectorFieldLabel sel_id] of
467 (rhs:rhss) -> ASSERT( null rhss )
469 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
470 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
472 labels = dataConFieldLabels data_con
476 then mapDs unlabelled_bottom arg_tys
477 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
478 `thenDs` \ con_args ->
480 returnDs (mkApps con_expr' con_args)
483 Record update is a little harder. Suppose we have the decl:
485 data T = T1 {op1, op2, op3 :: Int}
486 | T2 {op4, op2 :: Int}
489 Then we translate as follows:
495 T1 op1 _ op3 -> T1 op1 op2 op3
496 T2 op4 _ -> T2 op4 op2
497 other -> recUpdError "M.lhs/230"
499 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
500 RHSs, and do not generate a Core constructor application directly, because the constructor
501 might do some argument-evaluation first; and may have to throw away some
505 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
506 = getSrcLocDs `thenDs` \ src_loc ->
507 dsExpr record_expr `thenDs` \ record_expr' ->
509 -- Desugar the rbinds, and generate let-bindings if
510 -- necessary so that we don't lose sharing
513 record_in_ty = exprType record_expr'
514 (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
515 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
516 cons_to_upd = filter has_all_fields cons
518 mk_val_arg field old_arg_id
519 = case [rhs | (sel_id, rhs, _) <- rbinds,
520 field == recordSelectorFieldLabel sel_id] of
521 (rhs:rest) -> ASSERT(null rest) rhs
522 [] -> HsVar old_arg_id
525 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
526 -- This call to dataConArgTys won't work for existentials
528 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
529 (dataConFieldLabels con) arg_ids
530 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConId con))
535 returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
540 -- Record stuff doesn't work for existentials
541 ASSERT( all (not . isExistentialDataCon) cons )
543 -- It's important to generate the match with matchWrapper,
544 -- and the right hand sides with applications of the wrapper Id
545 -- so that everything works when we are doing fancy unboxing on the
546 -- constructor aguments.
547 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
548 matchWrapper RecUpdMatch alts "record update" `thenDs` \ ([discrim_var], matching_code) ->
550 returnDs (bindNonRec discrim_var record_expr' matching_code)
553 has_all_fields :: DataCon -> Bool
554 has_all_fields con_id
557 con_fields = dataConFieldLabels con_id
558 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
563 \underline{\bf Dictionary lambda and application}
564 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
565 @DictLam@ and @DictApp@ turn into the regular old things.
566 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
567 complicated; reminiscent of fully-applied constructors.
569 dsExpr (DictLam dictvars expr)
570 = dsExpr expr `thenDs` \ core_expr ->
571 returnDs (mkLams dictvars core_expr)
575 dsExpr (DictApp expr dicts) -- becomes a curried application
576 = dsExpr expr `thenDs` \ core_expr ->
577 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
583 -- HsSyn constructs that just shouldn't be here:
584 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
585 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
586 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
587 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
592 %--------------------------------------------------------------------
594 Basically does the translation given in the Haskell~1.3 report:
599 -> Id -- id for: return m
600 -> Id -- id for: (>>=) m
601 -> Id -- id for: fail m
602 -> Type -- Element type; the whole expression has type (m t)
605 dsDo do_or_lc stmts return_id then_id fail_id result_ty
607 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
610 = dsExpr expr `thenDs` \ expr2 ->
611 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
613 go (GuardStmt expr locn : stmts)
614 = do_expr expr locn `thenDs` \ expr2 ->
615 go stmts `thenDs` \ rest ->
616 let msg = ASSERT( isNotUsgTy b_ty )
617 "Pattern match failure in do expression, " ++ showSDoc (ppr locn) in
618 returnDs (mkIfThenElse expr2
620 (App (App (Var fail_id)
624 go (ExprStmt expr locn : stmts)
625 = do_expr expr locn `thenDs` \ expr2 ->
627 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
632 go stmts `thenDs` \ rest ->
633 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
634 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
635 Lam ignored_result_id rest])
637 go (LetStmt binds : stmts )
638 = go stmts `thenDs` \ rest ->
641 go (BindStmt pat expr locn : stmts)
643 dsExpr expr `thenDs` \ expr2 ->
645 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
646 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
647 (HsLitOut (HsString (_PK_ msg)) stringTy)
648 msg = ASSERT2( isNotUsgTy a_ty, ppr a_ty )
649 ASSERT2( isNotUsgTy b_ty, ppr b_ty )
650 "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
651 main_match = mkSimpleMatch [pat]
652 (HsDoOut do_or_lc stmts return_id then_id
653 fail_id result_ty locn)
654 (Just result_ty) locn
656 | failureFreePat pat = [main_match]
659 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
662 matchWrapper DoBindMatch the_matches match_msg
663 `thenDs` \ (binders, matching_code) ->
664 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
665 mkLams binders matching_code])
670 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
672 match_msg = case do_or_lc of
673 DoStmt -> "`do' statement"
674 ListComp -> "comprehension"
678 var_pat (WildPat _) = True
679 var_pat (VarPat _) = True
684 mkIntegerLit :: Integer -> CoreExpr
686 | inIntRange i -- Small enough, so start from an Int
687 = mkConApp smallIntegerDataCon [mkIntLit i]
689 | otherwise -- Big, so start from a string
690 = App (Var addr2IntegerId) (Lit (MachStr (_PK_ (show i))))