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,
25 import DsBinds ( dsMonoBinds )
26 import DsGRHSs ( dsGuarded )
27 import DsCCall ( dsCCall )
28 import DsListComp ( dsListComp )
29 import DsUtils ( mkErrorAppDs )
30 import Match ( matchWrapper, matchSimply )
32 import CoreUtils ( coreExprType )
33 import CostCentre ( mkUserCC )
34 import FieldLabel ( FieldLabel )
35 import Id ( Id, idType, recordSelectorFieldLabel )
36 import Const ( Con(..) )
37 import DataCon ( DataCon, dataConId, dataConTyCon, dataConArgTys, dataConFieldLabels )
38 import Const ( mkMachInt, Literal(..), mkStrLit )
39 import PrelVals ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID )
40 import TyCon ( isNewTyCon )
41 import DataCon ( isExistentialDataCon )
42 import Type ( splitFunTys, mkTyConApp,
43 splitAlgTyConApp, splitTyConApp_maybe,
44 splitAppTy, isUnLiftedType, Type
46 import TysWiredIn ( tupleCon, unboxedTupleCon,
47 consDataCon, listTyCon, mkListTy,
48 charDataCon, charTy, stringTy
50 import BasicTypes ( RecFlag(..) )
51 import Maybes ( maybeToBool )
52 import Util ( zipEqual, zipWithEqual )
57 %************************************************************************
61 %************************************************************************
63 @dsLet@ is a match-result transformer, taking the MatchResult for the body
64 and transforming it into one for the let-bindings enclosing the body.
66 This may seem a bit odd, but (source) let bindings can contain unboxed
71 This must be transformed to a case expression and, if the type has
72 more than one constructor, may fail.
75 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
80 dsLet (ThenBinds b1 b2) body
81 = dsLet b2 body `thenDs` \ body' ->
84 -- Special case for bindings which bind unlifted variables
85 dsLet (MonoBind (AbsBinds [] [] binder_triples (PatMonoBind pat grhss loc)) sigs is_rec) body
86 | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
87 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
89 dsGuarded grhss `thenDs` \ rhs ->
91 body' = foldr bind body binder_triples
92 bind (tyvars, g, l) body = ASSERT( null tyvars )
93 bindNonRec g (Var l) body
95 mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat)) `thenDs` \ error_expr ->
96 matchSimply rhs PatBindMatch pat body' error_expr
98 result_ty = coreExprType body
100 -- Ordinary case for bindings
101 dsLet (MonoBind binds sigs is_rec) body
102 = dsMonoBinds False binds [] `thenDs` \ prs ->
104 Recursive -> returnDs (Let (Rec prs) body)
105 NonRecursive -> returnDs (foldr mk_let body prs)
107 mk_let (bndr,rhs) body = Let (NonRec bndr rhs) body
110 %************************************************************************
112 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
114 %************************************************************************
117 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
119 dsExpr e@(HsVar var) = returnDs (Var var)
122 %************************************************************************
124 \subsection[DsExpr-literals]{Literals}
126 %************************************************************************
128 We give int/float literals type Integer and Rational, respectively.
129 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
132 ToDo: put in range checks for when converting "i"
133 (or should that be in the typechecker?)
135 For numeric literals, we try to detect there use at a standard type
136 (Int, Float, etc.) are directly put in the right constructor.
137 [NB: down with the @App@ conversion.]
138 Otherwise, we punt, putting in a "NoRep" Core literal (where the
139 representation decisions are delayed)...
141 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
144 dsExpr (HsLitOut (HsString s) _)
146 = returnDs (mkNilExpr charTy)
150 the_char = mkConApp charDataCon [mkLit (MachChar (_HEAD_ s))]
151 the_nil = mkNilExpr charTy
152 the_cons = mkConApp consDataCon [Type charTy, the_char, the_nil]
157 -- "_" => build (\ c n -> c 'c' n) -- LATER
159 -- "str" ==> build (\ c n -> foldr charTy T c n "str")
162 dsExpr (HsLitOut (HsString str) _)
163 = newTyVarsDs [alphaTyVar] `thenDs` \ [new_tyvar] ->
165 new_ty = mkTyVarTy new_tyvar
168 charTy `mkFunTy` (new_ty `mkFunTy` new_ty),
170 mkForallTy [alphaTyVar]
171 ((charTy `mkFunTy` (alphaTy `mkFunTy` alphaTy))
172 `mkFunTy` (alphaTy `mkFunTy` alphaTy))
173 ] `thenDs` \ [c,n,g] ->
174 returnDs (mkBuild charTy new_tyvar c n g (
176 (CoTyApp (CoTyApp (Var foldrId) charTy) new_ty) *** ensure non-prim type ***
177 [VarArg c,VarArg n,LitArg (NoRepStr str)]))
180 -- otherwise, leave it as a NoRepStr;
181 -- the Core-to-STG pass will wrap it in an application of "unpackCStringId".
183 dsExpr (HsLitOut (HsString str) _)
184 = returnDs (mkLit (NoRepStr str stringTy))
186 dsExpr (HsLitOut (HsLitLit str) ty)
187 = case (maybeBoxedPrimType ty) of
188 Just (boxing_data_con, prim_ty) ->
189 returnDs ( mkConApp boxing_data_con [mkLit (MachLitLit str prim_ty)] )
193 [ hcat [ text "Cannot see data constructor of ``literal-literal''s type: "
194 , text "value:", quotes (quotes (ptext str))
195 , text "; type: ", ppr ty
197 , text "Try compiling with -fno-prune-tydecls."
202 = case (maybeBoxedPrimType ty) of
203 Just (boxing_data_con, prim_ty) -> (boxing_data_con, prim_ty)
205 -> pprPanic "ERROR: ``literal-literal'' not a single-constructor type: "
206 (hcat [ptext str, text "; type: ", ppr ty])
208 dsExpr (HsLitOut (HsInt i) ty)
209 = returnDs (mkLit (NoRepInteger i ty))
211 dsExpr (HsLitOut (HsFrac r) ty)
212 = returnDs (mkLit (NoRepRational r ty))
214 -- others where we know what to do:
216 dsExpr (HsLitOut (HsIntPrim i) _)
217 | (i >= toInteger minInt && i <= toInteger maxInt)
218 = returnDs (mkLit (mkMachInt i))
220 = error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
222 dsExpr (HsLitOut (HsFloatPrim f) _)
223 = returnDs (mkLit (MachFloat f))
224 -- ToDo: range checking needed!
226 dsExpr (HsLitOut (HsDoublePrim d) _)
227 = returnDs (mkLit (MachDouble d))
228 -- ToDo: range checking needed!
230 dsExpr (HsLitOut (HsChar c) _)
231 = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
233 dsExpr (HsLitOut (HsCharPrim c) _)
234 = returnDs (mkLit (MachChar c))
236 dsExpr (HsLitOut (HsStringPrim s) _)
237 = returnDs (mkLit (MachStr s))
239 -- end of literals magic. --
241 dsExpr expr@(HsLam a_Match)
242 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
243 returnDs (mkLams binders matching_code)
245 dsExpr expr@(HsApp fun arg)
246 = dsExpr fun `thenDs` \ core_fun ->
247 dsExpr arg `thenDs` \ core_arg ->
248 returnDs (core_fun `App` core_arg)
252 Operator sections. At first it looks as if we can convert
261 But no! expr might be a redex, and we can lose laziness badly this
266 for example. So we convert instead to
268 let y = expr in \x -> op y x
270 If \tr{expr} is actually just a variable, say, then the simplifier
274 dsExpr (OpApp e1 op _ e2)
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 (coreExprType core_op)
280 dsExpr e1 `thenDs` \ x_core ->
281 dsExpr e2 `thenDs` \ y_core ->
282 returnDs (mkApps core_op [x_core, y_core])
284 dsExpr (SectionL expr op)
285 = dsExpr op `thenDs` \ core_op ->
286 -- for the type of y, we need the type of op's 2nd argument
288 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
290 dsExpr expr `thenDs` \ x_core ->
291 newSysLocalDs x_ty `thenDs` \ x_id ->
292 newSysLocalDs y_ty `thenDs` \ y_id ->
294 returnDs (bindNonRec x_id x_core $
295 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
297 -- dsExpr (SectionR op expr) -- \ x -> op x expr
298 dsExpr (SectionR op expr)
299 = dsExpr op `thenDs` \ core_op ->
300 -- for the type of x, we need the type of op's 2nd argument
302 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
304 dsExpr expr `thenDs` \ y_core ->
305 newSysLocalDs x_ty `thenDs` \ x_id ->
306 newSysLocalDs y_ty `thenDs` \ y_id ->
308 returnDs (bindNonRec y_id y_core $
309 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
311 dsExpr (CCall label args may_gc is_asm result_ty)
312 = mapDs dsExpr args `thenDs` \ core_args ->
313 dsCCall label core_args may_gc is_asm result_ty
314 -- dsCCall does all the unboxification, etc.
316 dsExpr (HsSCC cc expr)
317 = dsExpr expr `thenDs` \ core_expr ->
318 getModuleAndGroupDs `thenDs` \ (mod_name, group_name) ->
319 returnDs (Note (SCC (mkUserCC cc mod_name group_name)) core_expr)
321 -- special case to handle unboxed tuple patterns.
323 dsExpr (HsCase discrim matches@[Match _ [TuplePat ps boxed] _ _] src_loc)
324 | not boxed && all var_pat ps
325 = putSrcLocDs src_loc $
326 dsExpr discrim `thenDs` \ core_discrim ->
327 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
328 case matching_code of
329 Case (Var x) bndr alts | x == discrim_var ->
330 returnDs (Case core_discrim bndr alts)
331 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
333 dsExpr (HsCase discrim matches src_loc)
334 = putSrcLocDs src_loc $
335 dsExpr discrim `thenDs` \ core_discrim ->
336 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
337 returnDs (bindNonRec discrim_var core_discrim matching_code)
339 dsExpr (HsLet binds body)
340 = dsExpr body `thenDs` \ body' ->
343 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
344 | maybeToBool maybe_list_comp
345 = -- Special case for list comprehensions
346 putSrcLocDs src_loc $
347 dsListComp stmts elt_ty
350 = putSrcLocDs src_loc $
351 dsDo do_or_lc stmts return_id then_id fail_id result_ty
354 = case (do_or_lc, splitTyConApp_maybe result_ty) of
355 (ListComp, Just (tycon, [elt_ty]))
359 -- We need the ListComp form to use deListComp (rather than the "do" form)
360 -- because the "return" in a do block is a call to "PrelBase.return", and
361 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
363 Just elt_ty = maybe_list_comp
365 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
366 = putSrcLocDs src_loc $
367 dsExpr guard_expr `thenDs` \ core_guard ->
368 dsExpr then_expr `thenDs` \ core_then ->
369 dsExpr else_expr `thenDs` \ core_else ->
370 returnDs (mkIfThenElse core_guard core_then core_else)
374 Type lambda and application
375 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
377 dsExpr (TyLam tyvars expr)
378 = dsExpr expr `thenDs` \ core_expr ->
379 returnDs (mkLams tyvars core_expr)
381 dsExpr (TyApp expr tys)
382 = dsExpr expr `thenDs` \ core_expr ->
383 returnDs (mkTyApps core_expr tys)
387 Various data construction things
388 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
390 dsExpr (ExplicitListOut ty xs)
393 list_ty = mkListTy ty
395 go [] = returnDs (mkNilExpr ty)
396 go (x:xs) = dsExpr x `thenDs` \ core_x ->
397 go xs `thenDs` \ core_xs ->
398 returnDs (mkConApp consDataCon [Type ty, core_x, core_xs])
400 dsExpr (ExplicitTuple expr_list boxed)
401 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
402 returnDs (mkConApp ((if boxed
404 else unboxedTupleCon) (length expr_list))
405 (map (Type . coreExprType) core_exprs ++ core_exprs))
407 dsExpr (HsCon con_id [ty] [arg])
409 = dsExpr arg `thenDs` \ arg' ->
410 returnDs (Note (Coerce result_ty (coreExprType arg')) arg')
412 result_ty = mkTyConApp tycon [ty]
413 tycon = dataConTyCon con_id
415 dsExpr (HsCon con_id tys args)
416 = mapDs dsExpr args `thenDs` \ args2 ->
417 returnDs (mkConApp con_id (map Type tys ++ args2))
419 dsExpr (ArithSeqOut expr (From from))
420 = dsExpr expr `thenDs` \ expr2 ->
421 dsExpr from `thenDs` \ from2 ->
422 returnDs (App expr2 from2)
424 dsExpr (ArithSeqOut expr (FromTo from two))
425 = dsExpr expr `thenDs` \ expr2 ->
426 dsExpr from `thenDs` \ from2 ->
427 dsExpr two `thenDs` \ two2 ->
428 returnDs (mkApps expr2 [from2, two2])
430 dsExpr (ArithSeqOut expr (FromThen from thn))
431 = dsExpr expr `thenDs` \ expr2 ->
432 dsExpr from `thenDs` \ from2 ->
433 dsExpr thn `thenDs` \ thn2 ->
434 returnDs (mkApps expr2 [from2, thn2])
436 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
437 = dsExpr expr `thenDs` \ expr2 ->
438 dsExpr from `thenDs` \ from2 ->
439 dsExpr thn `thenDs` \ thn2 ->
440 dsExpr two `thenDs` \ two2 ->
441 returnDs (mkApps expr2 [from2, thn2, two2])
444 Record construction and update
445 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
446 For record construction we do this (assuming T has three arguments)
450 let err = /\a -> recConErr a
451 T (recConErr t1 "M.lhs/230/op1")
453 (recConErr t1 "M.lhs/230/op3")
455 recConErr then converts its arugment string into a proper message
456 before printing it as
458 M.lhs, line 230: missing field op1 was evaluated
462 dsExpr (RecordConOut data_con con_expr rbinds)
463 = dsExpr con_expr `thenDs` \ con_expr' ->
465 (arg_tys, _) = splitFunTys (coreExprType con_expr')
468 = case [rhs | (sel_id,rhs,_) <- rbinds,
469 lbl == recordSelectorFieldLabel sel_id] of
470 (rhs:rhss) -> ASSERT( null rhss )
472 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
474 mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys (dataConFieldLabels data_con)) `thenDs` \ con_args ->
475 returnDs (mkApps con_expr' con_args)
478 Record update is a little harder. Suppose we have the decl:
480 data T = T1 {op1, op2, op3 :: Int}
481 | T2 {op4, op2 :: Int}
484 Then we translate as follows:
490 T1 op1 _ op3 -> T1 op1 op2 op3
491 T2 op4 _ -> T2 op4 op2
492 other -> recUpdError "M.lhs/230"
494 It's important that we use the constructor Ids for T1, T2 etc on the
495 RHSs, and do not generate a Core Con directly, because the constructor
496 might do some argument-evaluation first; and may have to throw away some
500 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
501 = dsExpr record_expr `thenDs` \ record_expr' ->
503 -- Desugar the rbinds, and generate let-bindings if
504 -- necessary so that we don't lose sharing
507 ds_rbind (sel_id, rhs, pun_flag)
508 = dsExpr rhs `thenDs` \ rhs' ->
509 returnDs (recordSelectorFieldLabel sel_id, rhs')
511 mapDs ds_rbind rbinds `thenDs` \ rbinds' ->
513 record_in_ty = coreExprType 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 -- initial_args are passed to every constructor
519 initial_args = map Type out_inst_tys ++ map Var dicts
521 mk_val_arg field old_arg_id
522 = case [rhs | (f, rhs) <- rbinds', field == f] of
523 (rhs:rest) -> ASSERT(null rest) rhs
527 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
529 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
530 (dataConFieldLabels con) arg_ids
531 rhs = mkApps (mkApps (Var (dataConId con)) initial_args) val_args
533 returnDs (DataCon con, arg_ids, rhs)
536 | length cons_to_upd == length cons
539 = mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty "" `thenDs` \ err ->
540 returnDs [(DEFAULT, [], err)]
542 -- Record stuff doesn't work for existentials
543 ASSERT( all (not . isExistentialDataCon) cons )
545 newSysLocalDs record_in_ty `thenDs` \ case_bndr ->
546 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
547 mk_default `thenDs` \ deflt ->
549 returnDs (Case record_expr' case_bndr (alts ++ deflt))
551 has_all_fields :: DataCon -> Bool
552 has_all_fields con_id
555 con_fields = dataConFieldLabels con_id
556 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
559 Dictionary lambda and application
560 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
561 @DictLam@ and @DictApp@ turn into the regular old things.
562 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
563 complicated; reminiscent of fully-applied constructors.
565 dsExpr (DictLam dictvars expr)
566 = dsExpr expr `thenDs` \ core_expr ->
567 returnDs (mkLams dictvars core_expr)
571 dsExpr (DictApp expr dicts) -- becomes a curried application
572 = dsExpr expr `thenDs` \ core_expr ->
573 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
579 -- HsSyn constructs that just shouldn't be here:
580 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
581 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
582 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
583 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
586 out_of_range_msg -- ditto
587 = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
590 %--------------------------------------------------------------------
592 Basically does the translation given in the Haskell~1.3 report:
597 -> Id -- id for: return m
598 -> Id -- id for: (>>=) m
599 -> Id -- id for: fail m
600 -> Type -- Element type; the whole expression has type (m t)
603 dsDo do_or_lc stmts return_id then_id fail_id result_ty
605 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
608 = dsExpr expr `thenDs` \ expr2 ->
609 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
611 go (GuardStmt expr locn : stmts)
612 = do_expr expr locn `thenDs` \ expr2 ->
613 go stmts `thenDs` \ rest ->
614 let msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn) in
615 returnDs (mkIfThenElse expr2
617 (App (App (Var fail_id)
619 (mkLit (mkStrLit msg stringTy))))
621 go (ExprStmt expr locn : stmts)
622 = do_expr expr locn `thenDs` \ expr2 ->
624 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
629 go stmts `thenDs` \ rest ->
630 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
631 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
632 Lam ignored_result_id rest])
634 go (LetStmt binds : stmts )
635 = go stmts `thenDs` \ rest ->
638 go (BindStmt pat expr locn : stmts)
640 dsExpr expr `thenDs` \ expr2 ->
642 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
643 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty]) (HsLitOut (HsString (_PK_ msg)) stringTy)
644 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
645 main_match = mkSimpleMatch [pat]
646 (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty locn)
647 (Just result_ty) locn
649 | failureFreePat pat = [main_match]
652 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
655 matchWrapper DoBindMatch the_matches match_msg
656 `thenDs` \ (binders, matching_code) ->
657 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
658 mkLams binders matching_code])
663 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
665 match_msg = case do_or_lc of
666 DoStmt -> "`do' statement"
667 ListComp -> "comprehension"
671 var_pat (WildPat _) = True
672 var_pat (VarPat _) = True