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 PprCore ( {- instance Outputable Expr -} )
22 import CoreUtils ( exprType, mkIfThenElse, bindNonRec )
25 import DsBinds ( dsMonoBinds, AutoScc(..) )
26 import DsGRHSs ( dsGuarded )
27 import DsCCall ( dsCCall, resultWrapper )
28 import DsListComp ( dsListComp )
29 import DsUtils ( mkErrorAppDs, mkDsLets, mkStringLit, mkStringLitFS,
32 import Match ( matchWrapper, matchSimply )
34 import CostCentre ( mkUserCC )
35 import FieldLabel ( FieldLabel )
36 import Id ( Id, idType, recordSelectorFieldLabel )
37 import PrelInfo ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID )
38 import DataCon ( DataCon, dataConWrapId, dataConTyCon, dataConArgTys, dataConFieldLabels )
39 import TyCon ( isNewTyCon )
40 import DataCon ( isExistentialDataCon )
41 import Literal ( Literal(..), inIntRange )
42 import Type ( splitFunTys, mkTyConApp,
43 splitAlgTyConApp, splitAlgTyConApp_maybe, splitTyConApp_maybe,
45 splitAppTy, isUnLiftedType, Type
47 import TysWiredIn ( tupleCon,
49 charDataCon, charTy, stringTy,
50 smallIntegerDataCon, isIntegerTy
52 import BasicTypes ( RecFlag(..), Boxity(..) )
53 import Maybes ( maybeToBool )
54 import Unique ( Uniquable(..), hasKey, ratioTyConKey, addr2IntegerIdKey )
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) _)
167 dsExpr (HsLitOut (HsLitLit str) ty)
168 = ASSERT( maybeToBool maybe_ty )
169 returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
171 (maybe_ty, wrap_fn) = resultWrapper ty
172 Just rep_ty = maybe_ty
174 dsExpr (HsLitOut (HsInt i) ty)
178 dsExpr (HsLitOut (HsFrac r) ty)
179 = mkIntegerLit (numerator r) `thenDs` \ num ->
180 mkIntegerLit (denominator r) `thenDs` \ denom ->
181 returnDs (mkConApp ratio_data_con [Type integer_ty, num, denom])
183 (ratio_data_con, integer_ty)
184 = case (splitAlgTyConApp_maybe ty) of
185 Just (tycon, [i_ty], [con])
186 -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)
189 _ -> (panic "ratio_data_con", panic "integer_ty")
192 -- others where we know what to do:
194 dsExpr (HsLitOut (HsIntPrim i) _)
195 = returnDs (mkIntLit i)
197 dsExpr (HsLitOut (HsFloatPrim f) _)
198 = returnDs (mkLit (MachFloat f))
200 dsExpr (HsLitOut (HsDoublePrim d) _)
201 = returnDs (mkLit (MachDouble d))
202 -- ToDo: range checking needed!
204 dsExpr (HsLitOut (HsChar c) _)
205 = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
207 dsExpr (HsLitOut (HsCharPrim c) _)
208 = returnDs (mkLit (MachChar c))
210 dsExpr (HsLitOut (HsStringPrim s) _)
211 = returnDs (mkLit (MachStr s))
213 -- end of literals magic. --
215 dsExpr expr@(HsLam a_Match)
216 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
217 returnDs (mkLams binders matching_code)
219 dsExpr expr@(HsApp fun arg)
220 = dsExpr fun `thenDs` \ core_fun ->
221 dsExpr arg `thenDs` \ core_arg ->
222 returnDs (core_fun `App` core_arg)
226 Operator sections. At first it looks as if we can convert
235 But no! expr might be a redex, and we can lose laziness badly this
240 for example. So we convert instead to
242 let y = expr in \x -> op y x
244 If \tr{expr} is actually just a variable, say, then the simplifier
248 dsExpr (OpApp e1 op _ e2)
249 = dsExpr op `thenDs` \ core_op ->
250 -- for the type of y, we need the type of op's 2nd argument
251 dsExpr e1 `thenDs` \ x_core ->
252 dsExpr e2 `thenDs` \ y_core ->
253 returnDs (mkApps core_op [x_core, y_core])
255 dsExpr (SectionL expr op)
256 = dsExpr op `thenDs` \ core_op ->
257 -- for the type of y, we need the type of op's 2nd argument
259 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
261 dsExpr expr `thenDs` \ x_core ->
262 newSysLocalDs x_ty `thenDs` \ x_id ->
263 newSysLocalDs y_ty `thenDs` \ y_id ->
265 returnDs (bindNonRec x_id x_core $
266 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
268 -- dsExpr (SectionR op expr) -- \ x -> op x expr
269 dsExpr (SectionR op expr)
270 = dsExpr op `thenDs` \ core_op ->
271 -- for the type of x, we need the type of op's 2nd argument
273 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
275 dsExpr expr `thenDs` \ y_core ->
276 newSysLocalDs x_ty `thenDs` \ x_id ->
277 newSysLocalDs y_ty `thenDs` \ y_id ->
279 returnDs (bindNonRec y_id y_core $
280 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
282 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
283 = mapDs dsExpr args `thenDs` \ core_args ->
284 dsCCall lbl core_args may_gc is_asm result_ty
285 -- dsCCall does all the unboxification, etc.
287 dsExpr (HsSCC cc expr)
288 = dsExpr expr `thenDs` \ core_expr ->
289 getModuleDs `thenDs` \ mod_name ->
290 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
292 -- special case to handle unboxed tuple patterns.
294 dsExpr (HsCase discrim matches src_loc)
295 | all ubx_tuple_match matches
296 = putSrcLocDs src_loc $
297 dsExpr discrim `thenDs` \ core_discrim ->
298 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
299 case matching_code of
300 Case (Var x) bndr alts | x == discrim_var ->
301 returnDs (Case core_discrim bndr alts)
302 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
304 ubx_tuple_match (Match _ [TuplePat ps Unboxed] _ _) = True
305 ubx_tuple_match _ = False
307 dsExpr (HsCase discrim matches src_loc)
308 = putSrcLocDs src_loc $
309 dsExpr discrim `thenDs` \ core_discrim ->
310 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
311 returnDs (bindNonRec discrim_var core_discrim matching_code)
313 dsExpr (HsLet binds body)
314 = dsExpr body `thenDs` \ body' ->
317 dsExpr (HsWith expr binds)
318 = dsExpr expr `thenDs` \ expr' ->
319 foldlDs dsIPBind expr' binds
322 = dsExpr e `thenDs` \ e' ->
323 returnDs (Let (NonRec n e') body)
325 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
326 | maybeToBool maybe_list_comp
327 = -- Special case for list comprehensions
328 putSrcLocDs src_loc $
329 dsListComp stmts elt_ty
332 = putSrcLocDs src_loc $
333 dsDo do_or_lc stmts return_id then_id fail_id result_ty
336 = case (do_or_lc, splitTyConApp_maybe result_ty) of
337 (ListComp, Just (tycon, [elt_ty]))
341 -- We need the ListComp form to use deListComp (rather than the "do" form)
342 -- because the "return" in a do block is a call to "PrelBase.return", and
343 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
345 Just elt_ty = maybe_list_comp
347 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
348 = putSrcLocDs src_loc $
349 dsExpr guard_expr `thenDs` \ core_guard ->
350 dsExpr then_expr `thenDs` \ core_then ->
351 dsExpr else_expr `thenDs` \ core_else ->
352 returnDs (mkIfThenElse core_guard core_then core_else)
357 \underline{\bf Type lambda and application}
358 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
360 dsExpr (TyLam tyvars expr)
361 = dsExpr expr `thenDs` \ core_expr ->
362 returnDs (mkLams tyvars core_expr)
364 dsExpr (TyApp expr tys)
365 = dsExpr expr `thenDs` \ core_expr ->
366 returnDs (mkTyApps core_expr tys)
371 \underline{\bf Various data construction things}
372 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
374 dsExpr (ExplicitListOut ty xs)
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 boxity)
384 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
385 returnDs (mkConApp (tupleCon boxity (length expr_list))
386 (map (Type . unUsgTy . exprType) core_exprs ++ core_exprs))
387 -- the above unUsgTy is *required* -- KSW 1999-04-07
389 dsExpr (ArithSeqOut expr (From from))
390 = dsExpr expr `thenDs` \ expr2 ->
391 dsExpr from `thenDs` \ from2 ->
392 returnDs (App expr2 from2)
394 dsExpr (ArithSeqOut expr (FromTo from two))
395 = dsExpr expr `thenDs` \ expr2 ->
396 dsExpr from `thenDs` \ from2 ->
397 dsExpr two `thenDs` \ two2 ->
398 returnDs (mkApps expr2 [from2, two2])
400 dsExpr (ArithSeqOut expr (FromThen from thn))
401 = dsExpr expr `thenDs` \ expr2 ->
402 dsExpr from `thenDs` \ from2 ->
403 dsExpr thn `thenDs` \ thn2 ->
404 returnDs (mkApps expr2 [from2, thn2])
406 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
407 = dsExpr expr `thenDs` \ expr2 ->
408 dsExpr from `thenDs` \ from2 ->
409 dsExpr thn `thenDs` \ thn2 ->
410 dsExpr two `thenDs` \ two2 ->
411 returnDs (mkApps expr2 [from2, thn2, two2])
415 \underline{\bf Record construction and update}
416 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
417 For record construction we do this (assuming T has three arguments)
421 let err = /\a -> recConErr a
422 T (recConErr t1 "M.lhs/230/op1")
424 (recConErr t1 "M.lhs/230/op3")
426 @recConErr@ then converts its arugment string into a proper message
427 before printing it as
429 M.lhs, line 230: missing field op1 was evaluated
432 We also handle @C{}@ as valid construction syntax for an unlabelled
433 constructor @C@, setting all of @C@'s fields to bottom.
436 dsExpr (RecordConOut data_con con_expr rbinds)
437 = dsExpr con_expr `thenDs` \ con_expr' ->
439 (arg_tys, _) = splitFunTys (exprType con_expr')
442 = case [rhs | (sel_id,rhs,_) <- rbinds,
443 lbl == recordSelectorFieldLabel sel_id] of
444 (rhs:rhss) -> ASSERT( null rhss )
446 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
447 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
449 labels = dataConFieldLabels data_con
453 then mapDs unlabelled_bottom arg_tys
454 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
455 `thenDs` \ con_args ->
457 returnDs (mkApps con_expr' con_args)
460 Record update is a little harder. Suppose we have the decl:
462 data T = T1 {op1, op2, op3 :: Int}
463 | T2 {op4, op2 :: Int}
466 Then we translate as follows:
472 T1 op1 _ op3 -> T1 op1 op2 op3
473 T2 op4 _ -> T2 op4 op2
474 other -> recUpdError "M.lhs/230"
476 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
477 RHSs, and do not generate a Core constructor application directly, because the constructor
478 might do some argument-evaluation first; and may have to throw away some
482 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
483 = getSrcLocDs `thenDs` \ src_loc ->
484 dsExpr record_expr `thenDs` \ record_expr' ->
486 -- Desugar the rbinds, and generate let-bindings if
487 -- necessary so that we don't lose sharing
490 record_in_ty = exprType record_expr'
491 (_, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
492 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
493 cons_to_upd = filter has_all_fields cons
495 mk_val_arg field old_arg_id
496 = case [rhs | (sel_id, rhs, _) <- rbinds,
497 field == recordSelectorFieldLabel sel_id] of
498 (rhs:rest) -> ASSERT(null rest) rhs
499 [] -> HsVar old_arg_id
502 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
503 -- This call to dataConArgTys won't work for existentials
505 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
506 (dataConFieldLabels con) arg_ids
507 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConWrapId con))
512 returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
517 -- Record stuff doesn't work for existentials
518 ASSERT( all (not . isExistentialDataCon) cons )
520 -- It's important to generate the match with matchWrapper,
521 -- and the right hand sides with applications of the wrapper Id
522 -- so that everything works when we are doing fancy unboxing on the
523 -- constructor aguments.
524 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
525 matchWrapper RecUpdMatch alts "record update" `thenDs` \ ([discrim_var], matching_code) ->
527 returnDs (bindNonRec discrim_var record_expr' matching_code)
530 has_all_fields :: DataCon -> Bool
531 has_all_fields con_id
534 con_fields = dataConFieldLabels con_id
535 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
540 \underline{\bf Dictionary lambda and application}
541 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
542 @DictLam@ and @DictApp@ turn into the regular old things.
543 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
544 complicated; reminiscent of fully-applied constructors.
546 dsExpr (DictLam dictvars expr)
547 = dsExpr expr `thenDs` \ core_expr ->
548 returnDs (mkLams dictvars core_expr)
552 dsExpr (DictApp expr dicts) -- becomes a curried application
553 = dsExpr expr `thenDs` \ core_expr ->
554 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
560 -- HsSyn constructs that just shouldn't be here:
561 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
562 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
563 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
564 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
569 %--------------------------------------------------------------------
571 Basically does the translation given in the Haskell~1.3 report:
576 -> Id -- id for: return m
577 -> Id -- id for: (>>=) m
578 -> Id -- id for: fail m
579 -> Type -- Element type; the whole expression has type (m t)
582 dsDo do_or_lc stmts return_id then_id fail_id result_ty
584 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
587 = dsExpr expr `thenDs` \ expr2 ->
588 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
590 go (GuardStmt expr locn : stmts)
591 = do_expr expr locn `thenDs` \ expr2 ->
592 go stmts `thenDs` \ rest ->
593 let msg = ASSERT( isNotUsgTy b_ty )
594 "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
596 mkStringLit msg `thenDs` \ core_msg ->
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 -> DsM CoreExpr
665 | inIntRange i -- Small enough, so start from an Int
666 = returnDs (mkConApp smallIntegerDataCon [mkIntLit i])
668 | otherwise -- Big, so start from a string
669 = dsLookupGlobalValue addr2IntegerIdKey `thenDs` \ addr2IntegerId ->
670 returnDs (App (Var addr2IntegerId) (Lit (MachStr (_PK_ (show i)))))