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(..),
16 import TcHsSyn ( TypecheckedHsExpr, TypecheckedHsBinds,
24 import DsBinds ( dsMonoBinds )
25 import DsGRHSs ( dsGuarded )
26 import DsCCall ( dsCCall )
27 import DsListComp ( dsListComp )
28 import DsUtils ( mkErrorAppDs )
29 import Match ( matchWrapper, matchSimply )
31 import CoreUtils ( coreExprType )
32 import CostCentre ( mkUserCC )
33 import FieldLabel ( FieldLabel )
34 import Id ( Id, idType, recordSelectorFieldLabel )
35 import Const ( Con(..) )
36 import DataCon ( DataCon, dataConId, dataConTyCon, dataConArgTys, dataConFieldLabels )
37 import Const ( mkMachInt, Literal(..) )
38 import PrelVals ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID )
39 import TyCon ( isNewTyCon )
40 import DataCon ( isExistentialDataCon )
41 import Type ( splitFunTys, mkTyConApp,
42 splitAlgTyConApp, splitTyConApp_maybe,
43 splitAppTy, isUnLiftedType, Type
45 import TysWiredIn ( tupleCon, unboxedTupleCon,
46 consDataCon, listTyCon, mkListTy,
47 charDataCon, charTy, stringTy
49 import BasicTypes ( RecFlag(..) )
50 import Maybes ( maybeToBool )
51 import Util ( zipEqual, zipWithEqual )
56 %************************************************************************
60 %************************************************************************
62 @dsLet@ is a match-result transformer, taking the MatchResult for the body
63 and transforming it into one for the let-bindings enclosing the body.
65 This may seem a bit odd, but (source) let bindings can contain unboxed
70 This must be transformed to a case expression and, if the type has
71 more than one constructor, may fail.
74 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
79 dsLet (ThenBinds b1 b2) body
80 = dsLet b2 body `thenDs` \ body' ->
83 -- Special case for bindings which bind unlifted variables
84 dsLet (MonoBind (AbsBinds [] [] binder_triples bind) sigs is_rec) body
85 | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
86 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
88 dsGuarded grhss `thenDs` \ rhs ->
90 body' = foldr bind body binder_triples
91 bind (tyvars, g, l) body = ASSERT( null tyvars )
92 bindNonRec g (Var l) body
94 mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat)) `thenDs` \ error_expr ->
95 matchSimply rhs PatBindMatch pat body' error_expr
97 PatMonoBind pat grhss loc = bind
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 = returnDs ( mkConApp data_con [mkLit (MachLitLit str prim_ty)] )
190 = case (maybeBoxedPrimType ty) of
191 Just (boxing_data_con, prim_ty) -> (boxing_data_con, prim_ty)
193 -> pprPanic "ERROR: ``literal-literal'' not a single-constructor type: "
194 (hcat [ptext str, text "; type: ", ppr ty])
196 dsExpr (HsLitOut (HsInt i) ty)
197 = returnDs (mkLit (NoRepInteger i ty))
199 dsExpr (HsLitOut (HsFrac r) ty)
200 = returnDs (mkLit (NoRepRational r ty))
202 -- others where we know what to do:
204 dsExpr (HsLitOut (HsIntPrim i) _)
205 | (i >= toInteger minInt && i <= toInteger maxInt)
206 = returnDs (mkLit (mkMachInt i))
208 = error ("ERROR: Int constant " ++ show i ++ out_of_range_msg)
210 dsExpr (HsLitOut (HsFloatPrim f) _)
211 = returnDs (mkLit (MachFloat f))
212 -- ToDo: range checking needed!
214 dsExpr (HsLitOut (HsDoublePrim d) _)
215 = returnDs (mkLit (MachDouble d))
216 -- ToDo: range checking needed!
218 dsExpr (HsLitOut (HsChar c) _)
219 = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
221 dsExpr (HsLitOut (HsCharPrim c) _)
222 = returnDs (mkLit (MachChar c))
224 dsExpr (HsLitOut (HsStringPrim s) _)
225 = returnDs (mkLit (MachStr s))
227 -- end of literals magic. --
229 dsExpr expr@(HsLam a_Match)
230 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
231 returnDs (mkLams binders matching_code)
233 dsExpr expr@(HsApp fun arg)
234 = dsExpr fun `thenDs` \ core_fun ->
235 dsExpr arg `thenDs` \ core_arg ->
236 returnDs (core_fun `App` core_arg)
240 Operator sections. At first it looks as if we can convert
249 But no! expr might be a redex, and we can lose laziness badly this
254 for example. So we convert instead to
256 let y = expr in \x -> op y x
258 If \tr{expr} is actually just a variable, say, then the simplifier
262 dsExpr (OpApp e1 op _ e2)
263 = dsExpr op `thenDs` \ core_op ->
264 -- for the type of y, we need the type of op's 2nd argument
266 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
268 dsExpr e1 `thenDs` \ x_core ->
269 dsExpr e2 `thenDs` \ y_core ->
270 returnDs (mkApps core_op [x_core, y_core])
272 dsExpr (SectionL expr op)
273 = dsExpr op `thenDs` \ core_op ->
274 -- for the type of y, we need the type of op's 2nd argument
276 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
278 dsExpr expr `thenDs` \ x_core ->
279 newSysLocalDs x_ty `thenDs` \ x_id ->
280 newSysLocalDs y_ty `thenDs` \ y_id ->
282 returnDs (bindNonRec x_id x_core $
283 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
285 -- dsExpr (SectionR op expr) -- \ x -> op x expr
286 dsExpr (SectionR op expr)
287 = dsExpr op `thenDs` \ core_op ->
288 -- for the type of x, we need the type of op's 2nd argument
290 (x_ty:y_ty:_, _) = splitFunTys (coreExprType core_op)
292 dsExpr expr `thenDs` \ y_core ->
293 newSysLocalDs x_ty `thenDs` \ x_id ->
294 newSysLocalDs y_ty `thenDs` \ y_id ->
296 returnDs (bindNonRec y_id y_core $
297 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
299 dsExpr (CCall label args may_gc is_asm result_ty)
300 = mapDs dsExpr args `thenDs` \ core_args ->
301 dsCCall label core_args may_gc is_asm result_ty
302 -- dsCCall does all the unboxification, etc.
304 dsExpr (HsSCC cc expr)
305 = dsExpr expr `thenDs` \ core_expr ->
306 getModuleAndGroupDs `thenDs` \ (mod_name, group_name) ->
307 returnDs (Note (SCC (mkUserCC cc mod_name group_name)) core_expr)
309 -- special case to handle unboxed tuple patterns
311 dsExpr (HsCase discrim matches@[PatMatch (TuplePat ps boxed) (GRHSMatch rhs)]
314 = putSrcLocDs src_loc $
315 dsExpr discrim `thenDs` \ core_discrim ->
316 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
317 case matching_code of
318 Case (Var x) bndr alts | x == discrim_var ->
319 returnDs (Case core_discrim bndr alts)
320 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
322 dsExpr (HsCase discrim matches src_loc)
323 = putSrcLocDs src_loc $
324 dsExpr discrim `thenDs` \ core_discrim ->
325 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
326 returnDs (bindNonRec discrim_var core_discrim matching_code)
328 dsExpr (HsLet binds body)
329 = dsExpr body `thenDs` \ body' ->
332 dsExpr (HsDoOut do_or_lc stmts return_id then_id zero_id result_ty src_loc)
333 | maybeToBool maybe_list_comp
334 = -- Special case for list comprehensions
335 putSrcLocDs src_loc $
336 dsListComp stmts elt_ty
339 = putSrcLocDs src_loc $
340 dsDo do_or_lc stmts return_id then_id zero_id result_ty
343 = case (do_or_lc, splitTyConApp_maybe result_ty) of
344 (ListComp, Just (tycon, [elt_ty]))
348 -- We need the ListComp form to use deListComp (rather than the "do" form)
349 -- because the "return" in a do block is a call to "PrelBase.return", and
350 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
352 Just elt_ty = maybe_list_comp
354 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
355 = putSrcLocDs src_loc $
356 dsExpr guard_expr `thenDs` \ core_guard ->
357 dsExpr then_expr `thenDs` \ core_then ->
358 dsExpr else_expr `thenDs` \ core_else ->
359 returnDs (mkIfThenElse core_guard core_then core_else)
363 Type lambda and application
364 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
366 dsExpr (TyLam tyvars expr)
367 = dsExpr expr `thenDs` \ core_expr ->
368 returnDs (mkLams tyvars core_expr)
370 dsExpr (TyApp expr tys)
371 = dsExpr expr `thenDs` \ core_expr ->
372 returnDs (mkTyApps core_expr tys)
376 Various data construction things
377 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
379 dsExpr (ExplicitListOut ty xs)
382 list_ty = mkListTy ty
384 go [] = returnDs (mkNilExpr ty)
385 go (x:xs) = dsExpr x `thenDs` \ core_x ->
386 go xs `thenDs` \ core_xs ->
387 returnDs (mkConApp consDataCon [Type ty, core_x, core_xs])
389 dsExpr (ExplicitTuple expr_list boxed)
390 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
391 returnDs (mkConApp ((if boxed
393 else unboxedTupleCon) (length expr_list))
394 (map (Type . coreExprType) core_exprs ++ core_exprs))
396 dsExpr (HsCon con_id [ty] [arg])
398 = dsExpr arg `thenDs` \ arg' ->
399 returnDs (Note (Coerce result_ty (coreExprType arg')) arg')
401 result_ty = mkTyConApp tycon [ty]
402 tycon = dataConTyCon con_id
404 dsExpr (HsCon con_id tys args)
405 = mapDs dsExpr args `thenDs` \ args2 ->
406 returnDs (mkConApp con_id (map Type tys ++ args2))
408 dsExpr (ArithSeqOut expr (From from))
409 = dsExpr expr `thenDs` \ expr2 ->
410 dsExpr from `thenDs` \ from2 ->
411 returnDs (App expr2 from2)
413 dsExpr (ArithSeqOut expr (FromTo from two))
414 = dsExpr expr `thenDs` \ expr2 ->
415 dsExpr from `thenDs` \ from2 ->
416 dsExpr two `thenDs` \ two2 ->
417 returnDs (mkApps expr2 [from2, two2])
419 dsExpr (ArithSeqOut expr (FromThen from thn))
420 = dsExpr expr `thenDs` \ expr2 ->
421 dsExpr from `thenDs` \ from2 ->
422 dsExpr thn `thenDs` \ thn2 ->
423 returnDs (mkApps expr2 [from2, thn2])
425 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
426 = dsExpr expr `thenDs` \ expr2 ->
427 dsExpr from `thenDs` \ from2 ->
428 dsExpr thn `thenDs` \ thn2 ->
429 dsExpr two `thenDs` \ two2 ->
430 returnDs (mkApps expr2 [from2, thn2, two2])
433 Record construction and update
434 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
435 For record construction we do this (assuming T has three arguments)
439 let err = /\a -> recConErr a
440 T (recConErr t1 "M.lhs/230/op1")
442 (recConErr t1 "M.lhs/230/op3")
444 recConErr then converts its arugment string into a proper message
445 before printing it as
447 M.lhs, line 230: missing field op1 was evaluated
451 dsExpr (RecordConOut data_con con_expr rbinds)
452 = dsExpr con_expr `thenDs` \ con_expr' ->
454 (arg_tys, _) = splitFunTys (coreExprType con_expr')
457 = case [rhs | (sel_id,rhs,_) <- rbinds,
458 lbl == recordSelectorFieldLabel sel_id] of
459 (rhs:rhss) -> ASSERT( null rhss )
461 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
463 mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys (dataConFieldLabels data_con)) `thenDs` \ con_args ->
464 returnDs (mkApps con_expr' con_args)
467 Record update is a little harder. Suppose we have the decl:
469 data T = T1 {op1, op2, op3 :: Int}
470 | T2 {op4, op2 :: Int}
473 Then we translate as follows:
479 T1 op1 _ op3 -> T1 op1 op2 op3
480 T2 op4 _ -> T2 op4 op2
481 other -> recUpdError "M.lhs/230"
483 It's important that we use the constructor Ids for T1, T2 etc on the
484 RHSs, and do not generate a Core Con directly, because the constructor
485 might do some argument-evaluation first; and may have to throw away some
489 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
490 = dsExpr record_expr `thenDs` \ record_expr' ->
492 -- Desugar the rbinds, and generate let-bindings if
493 -- necessary so that we don't lose sharing
496 ds_rbind (sel_id, rhs, pun_flag)
497 = dsExpr rhs `thenDs` \ rhs' ->
498 returnDs (recordSelectorFieldLabel sel_id, rhs')
500 mapDs ds_rbind rbinds `thenDs` \ rbinds' ->
502 record_in_ty = coreExprType record_expr'
503 (tycon, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
504 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
505 cons_to_upd = filter has_all_fields cons
507 -- initial_args are passed to every constructor
508 initial_args = map Type out_inst_tys ++ map Var dicts
510 mk_val_arg field old_arg_id
511 = case [rhs | (f, rhs) <- rbinds', field == f] of
512 (rhs:rest) -> ASSERT(null rest) rhs
516 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
518 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
519 (dataConFieldLabels con) arg_ids
520 rhs = mkApps (mkApps (Var (dataConId con)) initial_args) val_args
522 returnDs (DataCon con, arg_ids, rhs)
525 | length cons_to_upd == length cons
528 = mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty "" `thenDs` \ err ->
529 returnDs [(DEFAULT, [], err)]
531 -- Record stuff doesn't work for existentials
532 ASSERT( all (not . isExistentialDataCon) cons )
534 newSysLocalDs record_in_ty `thenDs` \ case_bndr ->
535 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
536 mk_default `thenDs` \ deflt ->
538 returnDs (Case record_expr' case_bndr (alts ++ deflt))
540 has_all_fields :: DataCon -> Bool
541 has_all_fields con_id
544 con_fields = dataConFieldLabels con_id
545 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
548 Dictionary lambda and application
549 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
550 @DictLam@ and @DictApp@ turn into the regular old things.
551 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
552 complicated; reminiscent of fully-applied constructors.
554 dsExpr (DictLam dictvars expr)
555 = dsExpr expr `thenDs` \ core_expr ->
556 returnDs (mkLams dictvars core_expr)
560 dsExpr (DictApp expr dicts) -- becomes a curried application
561 = dsExpr expr `thenDs` \ core_expr ->
562 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
569 -- HsSyn constructs that just shouldn't be here:
570 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
571 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
572 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
573 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
576 out_of_range_msg -- ditto
577 = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
580 %--------------------------------------------------------------------
582 Basically does the translation given in the Haskell~1.3 report:
587 -> Id -- id for: return m
588 -> Id -- id for: (>>=) m
589 -> Id -- id for: zero m
590 -> Type -- Element type; the whole expression has type (m t)
593 dsDo do_or_lc stmts return_id then_id zero_id result_ty
595 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
598 = dsExpr expr `thenDs` \ expr2 ->
599 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
601 go (GuardStmt expr locn : stmts)
602 = do_expr expr locn `thenDs` \ expr2 ->
603 go stmts `thenDs` \ rest ->
604 returnDs (mkIfThenElse expr2 rest (App (Var zero_id) (Type b_ty)))
606 go (ExprStmt expr locn : stmts)
607 = do_expr expr locn `thenDs` \ expr2 ->
609 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
614 go stmts `thenDs` \ rest ->
615 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
616 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
617 Lam ignored_result_id rest])
619 go (LetStmt binds : stmts )
620 = go stmts `thenDs` \ rest ->
623 go (BindStmt pat expr locn : stmts)
625 dsExpr expr `thenDs` \ expr2 ->
627 (_, a_ty) = splitAppTy (coreExprType expr2) -- Must be of form (m a)
628 zero_expr = TyApp (HsVar zero_id) [b_ty]
629 main_match = PatMatch pat (SimpleMatch (
630 HsDoOut do_or_lc stmts return_id then_id zero_id result_ty locn))
632 = if failureFreePat pat
634 else [main_match, PatMatch (WildPat a_ty) (SimpleMatch zero_expr)]
636 matchWrapper DoBindMatch the_matches match_msg
637 `thenDs` \ (binders, matching_code) ->
638 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
639 mkLams binders matching_code])
644 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
646 match_msg = case do_or_lc of
647 DoStmt -> "`do' statement"
648 ListComp -> "comprehension"
652 var_pat (WildPat _) = True
653 var_pat (VarPat _) = True