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, mkConsExpr, mkNilExpr )
30 import Match ( matchWrapper, matchSimply )
32 import CostCentre ( mkUserCC )
33 import FieldLabel ( FieldLabel )
34 import Id ( Id, idType, recordSelectorFieldLabel )
35 import DataCon ( DataCon, dataConWrapId, dataConTyCon, dataConArgTys, dataConFieldLabels )
36 import PrelInfo ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID, addr2IntegerId )
37 import TyCon ( isNewTyCon )
38 import DataCon ( isExistentialDataCon )
39 import Literal ( Literal(..), inIntRange )
40 import Type ( splitFunTys, mkTyConApp,
41 splitAlgTyConApp, splitAlgTyConApp_maybe, splitTyConApp_maybe,
43 splitAppTy, isUnLiftedType, Type
45 import TysWiredIn ( tupleCon, unboxedTupleCon,
47 charDataCon, charTy, stringTy,
48 smallIntegerDataCon, isIntegerTy
50 import BasicTypes ( RecFlag(..) )
51 import Maybes ( maybeToBool )
52 import Unique ( Uniquable(..), ratioTyConKey )
53 import Util ( zipEqual, zipWithEqual )
56 import Ratio ( numerator, denominator )
60 %************************************************************************
64 %************************************************************************
66 @dsLet@ is a match-result transformer, taking the @MatchResult@ for the body
67 and transforming it into one for the let-bindings enclosing the body.
69 This may seem a bit odd, but (source) let bindings can contain unboxed
74 This must be transformed to a case expression and, if the type has
75 more than one constructor, may fail.
78 dsLet :: TypecheckedHsBinds -> CoreExpr -> DsM CoreExpr
83 dsLet (ThenBinds b1 b2) body
84 = dsLet b2 body `thenDs` \ body' ->
87 -- Special case for bindings which bind unlifted variables
88 -- Silently ignore INLINE pragmas...
89 dsLet (MonoBind (AbsBinds [] [] binder_triples inlines
90 (PatMonoBind pat grhss loc)) sigs is_rec) body
91 | or [isUnLiftedType (idType g) | (_, g, l) <- binder_triples]
92 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
94 dsGuarded grhss `thenDs` \ rhs ->
96 body' = foldr bind body binder_triples
97 bind (tyvars, g, l) body = ASSERT( null tyvars )
98 bindNonRec g (Var l) body
100 mkErrorAppDs iRREFUT_PAT_ERROR_ID result_ty (showSDoc (ppr pat))
101 `thenDs` \ error_expr ->
102 matchSimply rhs PatBindMatch pat body' error_expr
104 result_ty = exprType body
106 -- Ordinary case for bindings
107 dsLet (MonoBind binds sigs is_rec) body
108 = dsMonoBinds NoSccs binds [] `thenDs` \ prs ->
110 Recursive -> returnDs (Let (Rec prs) body)
111 NonRecursive -> returnDs (mkDsLets [NonRec b r | (b,r) <- prs] body)
114 %************************************************************************
116 \subsection[DsExpr-vars-and-cons]{Variables and constructors}
118 %************************************************************************
121 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
123 dsExpr e@(HsVar var) = returnDs (Var var)
124 dsExpr e@(HsIPVar var) = returnDs (Var var)
127 %************************************************************************
129 \subsection[DsExpr-literals]{Literals}
131 %************************************************************************
133 We give int/float literals type @Integer@ and @Rational@, respectively.
134 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
137 ToDo: put in range checks for when converting ``@i@''
138 (or should that be in the typechecker?)
140 For numeric literals, we try to detect there use at a standard type
141 (@Int@, @Float@, etc.) are directly put in the right constructor.
142 [NB: down with the @App@ conversion.]
144 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
147 dsExpr (HsLitOut (HsString s) _)
149 = returnDs (mkNilExpr charTy)
153 the_char = mkConApp charDataCon [mkLit (MachChar (_HEAD_ s))]
154 the_nil = mkNilExpr charTy
155 the_cons = mkConsExpr charTy the_char the_nil
160 -- "_" => build (\ c n -> c 'c' n) -- LATER
162 dsExpr (HsLitOut (HsString str) _)
163 = returnDs (mkStringLitFS str)
165 dsExpr (HsLitOut (HsLitLit str) ty)
166 = ASSERT( maybeToBool maybe_ty )
167 returnDs (wrap_fn (mkLit (MachLitLit str rep_ty)))
169 (maybe_ty, wrap_fn) = resultWrapper ty
170 Just rep_ty = maybe_ty
172 dsExpr (HsLitOut (HsInt i) ty)
173 = returnDs (mkIntegerLit i)
176 dsExpr (HsLitOut (HsFrac r) ty)
177 = returnDs (mkConApp ratio_data_con [Type integer_ty,
178 mkIntegerLit (numerator r),
179 mkIntegerLit (denominator r)])
181 (ratio_data_con, integer_ty)
182 = case (splitAlgTyConApp_maybe ty) of
183 Just (tycon, [i_ty], [con])
184 -> ASSERT(isIntegerTy i_ty && getUnique tycon == ratioTyConKey)
187 _ -> (panic "ratio_data_con", panic "integer_ty")
191 -- others where we know what to do:
193 dsExpr (HsLitOut (HsIntPrim i) _)
194 = returnDs (mkIntLit i)
196 dsExpr (HsLitOut (HsFloatPrim f) _)
197 = returnDs (mkLit (MachFloat f))
199 dsExpr (HsLitOut (HsDoublePrim d) _)
200 = returnDs (mkLit (MachDouble d))
201 -- ToDo: range checking needed!
203 dsExpr (HsLitOut (HsChar c) _)
204 = returnDs ( mkConApp charDataCon [mkLit (MachChar c)] )
206 dsExpr (HsLitOut (HsCharPrim c) _)
207 = returnDs (mkLit (MachChar c))
209 dsExpr (HsLitOut (HsStringPrim s) _)
210 = returnDs (mkLit (MachStr s))
212 -- end of literals magic. --
214 dsExpr expr@(HsLam a_Match)
215 = matchWrapper LambdaMatch [a_Match] "lambda" `thenDs` \ (binders, matching_code) ->
216 returnDs (mkLams binders matching_code)
218 dsExpr expr@(HsApp fun arg)
219 = dsExpr fun `thenDs` \ core_fun ->
220 dsExpr arg `thenDs` \ core_arg ->
221 returnDs (core_fun `App` core_arg)
225 Operator sections. At first it looks as if we can convert
234 But no! expr might be a redex, and we can lose laziness badly this
239 for example. So we convert instead to
241 let y = expr in \x -> op y x
243 If \tr{expr} is actually just a variable, say, then the simplifier
247 dsExpr (OpApp e1 op _ e2)
248 = dsExpr op `thenDs` \ core_op ->
249 -- for the type of y, we need the type of op's 2nd argument
250 dsExpr e1 `thenDs` \ x_core ->
251 dsExpr e2 `thenDs` \ y_core ->
252 returnDs (mkApps core_op [x_core, y_core])
254 dsExpr (SectionL expr op)
255 = dsExpr op `thenDs` \ core_op ->
256 -- for the type of y, we need the type of op's 2nd argument
258 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
260 dsExpr expr `thenDs` \ x_core ->
261 newSysLocalDs x_ty `thenDs` \ x_id ->
262 newSysLocalDs y_ty `thenDs` \ y_id ->
264 returnDs (bindNonRec x_id x_core $
265 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
267 -- dsExpr (SectionR op expr) -- \ x -> op x expr
268 dsExpr (SectionR op expr)
269 = dsExpr op `thenDs` \ core_op ->
270 -- for the type of x, we need the type of op's 2nd argument
272 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
274 dsExpr expr `thenDs` \ y_core ->
275 newSysLocalDs x_ty `thenDs` \ x_id ->
276 newSysLocalDs y_ty `thenDs` \ y_id ->
278 returnDs (bindNonRec y_id y_core $
279 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
281 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
282 = mapDs dsExpr args `thenDs` \ core_args ->
283 dsCCall lbl core_args may_gc is_asm result_ty
284 -- dsCCall does all the unboxification, etc.
286 dsExpr (HsSCC cc expr)
287 = dsExpr expr `thenDs` \ core_expr ->
288 getModuleDs `thenDs` \ mod_name ->
289 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
291 -- special case to handle unboxed tuple patterns.
293 dsExpr (HsCase discrim matches src_loc)
294 | all ubx_tuple_match matches
295 = putSrcLocDs src_loc $
296 dsExpr discrim `thenDs` \ core_discrim ->
297 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
298 case matching_code of
299 Case (Var x) bndr alts | x == discrim_var ->
300 returnDs (Case core_discrim bndr alts)
301 _ -> panic ("dsExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
303 ubx_tuple_match (Match _ [TuplePat ps False{-unboxed-}] _ _) = True
304 ubx_tuple_match _ = False
306 dsExpr (HsCase discrim matches src_loc)
307 = putSrcLocDs src_loc $
308 dsExpr discrim `thenDs` \ core_discrim ->
309 matchWrapper CaseMatch matches "case" `thenDs` \ ([discrim_var], matching_code) ->
310 returnDs (bindNonRec discrim_var core_discrim matching_code)
312 dsExpr (HsLet binds body)
313 = dsExpr body `thenDs` \ body' ->
316 dsExpr (HsWith expr binds)
317 = dsExpr expr `thenDs` \ expr' ->
318 foldlDs dsIPBind expr' binds
321 = dsExpr e `thenDs` \ e' ->
322 returnDs (Let (NonRec n e') body)
324 dsExpr (HsDoOut do_or_lc stmts return_id then_id fail_id result_ty src_loc)
325 | maybeToBool maybe_list_comp
326 = -- Special case for list comprehensions
327 putSrcLocDs src_loc $
328 dsListComp stmts elt_ty
331 = putSrcLocDs src_loc $
332 dsDo do_or_lc stmts return_id then_id fail_id result_ty
335 = case (do_or_lc, splitTyConApp_maybe result_ty) of
336 (ListComp, Just (tycon, [elt_ty]))
340 -- We need the ListComp form to use deListComp (rather than the "do" form)
341 -- because the "return" in a do block is a call to "PrelBase.return", and
342 -- not a ReturnStmt. Only the ListComp form has ReturnStmts
344 Just elt_ty = maybe_list_comp
346 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
347 = putSrcLocDs src_loc $
348 dsExpr guard_expr `thenDs` \ core_guard ->
349 dsExpr then_expr `thenDs` \ core_then ->
350 dsExpr else_expr `thenDs` \ core_else ->
351 returnDs (mkIfThenElse core_guard core_then core_else)
356 \underline{\bf Type lambda and application}
357 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
359 dsExpr (TyLam tyvars expr)
360 = dsExpr expr `thenDs` \ core_expr ->
361 returnDs (mkLams tyvars core_expr)
363 dsExpr (TyApp expr tys)
364 = dsExpr expr `thenDs` \ core_expr ->
365 returnDs (mkTyApps core_expr tys)
370 \underline{\bf Various data construction things}
371 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
373 dsExpr (ExplicitListOut ty xs)
376 go [] = returnDs (mkNilExpr ty)
377 go (x:xs) = dsExpr x `thenDs` \ core_x ->
378 go xs `thenDs` \ core_xs ->
379 ASSERT( isNotUsgTy ty )
380 returnDs (mkConsExpr ty core_x core_xs)
382 dsExpr (ExplicitTuple expr_list boxed)
383 = mapDs dsExpr expr_list `thenDs` \ core_exprs ->
384 returnDs (mkConApp ((if boxed
386 else unboxedTupleCon) (length expr_list))
387 (map (Type . unUsgTy . exprType) core_exprs ++ core_exprs))
388 -- the above unUsgTy is *required* -- KSW 1999-04-07
390 dsExpr (ArithSeqOut expr (From from))
391 = dsExpr expr `thenDs` \ expr2 ->
392 dsExpr from `thenDs` \ from2 ->
393 returnDs (App expr2 from2)
395 dsExpr (ArithSeqOut expr (FromTo from two))
396 = dsExpr expr `thenDs` \ expr2 ->
397 dsExpr from `thenDs` \ from2 ->
398 dsExpr two `thenDs` \ two2 ->
399 returnDs (mkApps expr2 [from2, two2])
401 dsExpr (ArithSeqOut expr (FromThen from thn))
402 = dsExpr expr `thenDs` \ expr2 ->
403 dsExpr from `thenDs` \ from2 ->
404 dsExpr thn `thenDs` \ thn2 ->
405 returnDs (mkApps expr2 [from2, thn2])
407 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
408 = dsExpr expr `thenDs` \ expr2 ->
409 dsExpr from `thenDs` \ from2 ->
410 dsExpr thn `thenDs` \ thn2 ->
411 dsExpr two `thenDs` \ two2 ->
412 returnDs (mkApps expr2 [from2, thn2, two2])
416 \underline{\bf Record construction and update}
417 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
418 For record construction we do this (assuming T has three arguments)
422 let err = /\a -> recConErr a
423 T (recConErr t1 "M.lhs/230/op1")
425 (recConErr t1 "M.lhs/230/op3")
427 @recConErr@ then converts its arugment string into a proper message
428 before printing it as
430 M.lhs, line 230: missing field op1 was evaluated
433 We also handle @C{}@ as valid construction syntax for an unlabelled
434 constructor @C@, setting all of @C@'s fields to bottom.
437 dsExpr (RecordConOut data_con con_expr rbinds)
438 = dsExpr con_expr `thenDs` \ con_expr' ->
440 (arg_tys, _) = splitFunTys (exprType con_expr')
443 = case [rhs | (sel_id,rhs,_) <- rbinds,
444 lbl == recordSelectorFieldLabel sel_id] of
445 (rhs:rhss) -> ASSERT( null rhss )
447 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
448 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
450 labels = dataConFieldLabels data_con
454 then mapDs unlabelled_bottom arg_tys
455 else mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
456 `thenDs` \ con_args ->
458 returnDs (mkApps con_expr' con_args)
461 Record update is a little harder. Suppose we have the decl:
463 data T = T1 {op1, op2, op3 :: Int}
464 | T2 {op4, op2 :: Int}
467 Then we translate as follows:
473 T1 op1 _ op3 -> T1 op1 op2 op3
474 T2 op4 _ -> T2 op4 op2
475 other -> recUpdError "M.lhs/230"
477 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
478 RHSs, and do not generate a Core constructor application directly, because the constructor
479 might do some argument-evaluation first; and may have to throw away some
483 dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
484 = getSrcLocDs `thenDs` \ src_loc ->
485 dsExpr record_expr `thenDs` \ record_expr' ->
487 -- Desugar the rbinds, and generate let-bindings if
488 -- necessary so that we don't lose sharing
491 record_in_ty = exprType record_expr'
492 (_, in_inst_tys, cons) = splitAlgTyConApp record_in_ty
493 (_, out_inst_tys, _) = splitAlgTyConApp record_out_ty
494 cons_to_upd = filter has_all_fields cons
496 mk_val_arg field old_arg_id
497 = case [rhs | (sel_id, rhs, _) <- rbinds,
498 field == recordSelectorFieldLabel sel_id] of
499 (rhs:rest) -> ASSERT(null rest) rhs
500 [] -> HsVar old_arg_id
503 = newSysLocalsDs (dataConArgTys con in_inst_tys) `thenDs` \ arg_ids ->
504 -- This call to dataConArgTys won't work for existentials
506 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
507 (dataConFieldLabels con) arg_ids
508 rhs = foldl HsApp (DictApp (TyApp (HsVar (dataConWrapId con))
513 returnDs (mkSimpleMatch [ConPat con record_in_ty [] [] (map VarPat arg_ids)]
518 -- Record stuff doesn't work for existentials
519 ASSERT( all (not . isExistentialDataCon) cons )
521 -- It's important to generate the match with matchWrapper,
522 -- and the right hand sides with applications of the wrapper Id
523 -- so that everything works when we are doing fancy unboxing on the
524 -- constructor aguments.
525 mapDs mk_alt cons_to_upd `thenDs` \ alts ->
526 matchWrapper RecUpdMatch alts "record update" `thenDs` \ ([discrim_var], matching_code) ->
528 returnDs (bindNonRec discrim_var record_expr' matching_code)
531 has_all_fields :: DataCon -> Bool
532 has_all_fields con_id
535 con_fields = dataConFieldLabels con_id
536 ok (sel_id, _, _) = recordSelectorFieldLabel sel_id `elem` con_fields
541 \underline{\bf Dictionary lambda and application}
542 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
543 @DictLam@ and @DictApp@ turn into the regular old things.
544 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
545 complicated; reminiscent of fully-applied constructors.
547 dsExpr (DictLam dictvars expr)
548 = dsExpr expr `thenDs` \ core_expr ->
549 returnDs (mkLams dictvars core_expr)
553 dsExpr (DictApp expr dicts) -- becomes a curried application
554 = dsExpr expr `thenDs` \ core_expr ->
555 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
561 -- HsSyn constructs that just shouldn't be here:
562 dsExpr (HsDo _ _ _) = panic "dsExpr:HsDo"
563 dsExpr (ExplicitList _) = panic "dsExpr:ExplicitList"
564 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
565 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
570 %--------------------------------------------------------------------
572 Basically does the translation given in the Haskell~1.3 report:
577 -> Id -- id for: return m
578 -> Id -- id for: (>>=) m
579 -> Id -- id for: fail m
580 -> Type -- Element type; the whole expression has type (m t)
583 dsDo do_or_lc stmts return_id then_id fail_id result_ty
585 (_, b_ty) = splitAppTy result_ty -- result_ty must be of the form (m b)
588 = dsExpr expr `thenDs` \ expr2 ->
589 returnDs (mkApps (Var return_id) [Type b_ty, expr2])
591 go (GuardStmt expr locn : stmts)
592 = do_expr expr locn `thenDs` \ expr2 ->
593 go stmts `thenDs` \ rest ->
594 let msg = ASSERT( isNotUsgTy b_ty )
595 "Pattern match failure in do expression, " ++ showSDoc (ppr locn) in
596 returnDs (mkIfThenElse expr2
598 (App (App (Var fail_id)
602 go (ExprStmt expr locn : stmts)
603 = do_expr expr locn `thenDs` \ expr2 ->
605 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
610 go stmts `thenDs` \ rest ->
611 newSysLocalDs a_ty `thenDs` \ ignored_result_id ->
612 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
613 Lam ignored_result_id rest])
615 go (LetStmt binds : stmts )
616 = go stmts `thenDs` \ rest ->
619 go (BindStmt pat expr locn : stmts)
621 dsExpr expr `thenDs` \ expr2 ->
623 (_, a_ty) = splitAppTy (exprType expr2) -- Must be of form (m a)
624 fail_expr = HsApp (TyApp (HsVar fail_id) [b_ty])
625 (HsLitOut (HsString (_PK_ msg)) stringTy)
626 msg = ASSERT2( isNotUsgTy a_ty, ppr a_ty )
627 ASSERT2( isNotUsgTy b_ty, ppr b_ty )
628 "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
629 main_match = mkSimpleMatch [pat]
630 (HsDoOut do_or_lc stmts return_id then_id
631 fail_id result_ty locn)
632 (Just result_ty) locn
634 | failureFreePat pat = [main_match]
637 , mkSimpleMatch [WildPat a_ty] fail_expr (Just result_ty) locn
640 matchWrapper DoBindMatch the_matches match_msg
641 `thenDs` \ (binders, matching_code) ->
642 returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2,
643 mkLams binders matching_code])
648 do_expr expr locn = putSrcLocDs locn (dsExpr expr)
650 match_msg = case do_or_lc of
651 DoStmt -> "`do' statement"
652 ListComp -> "comprehension"
656 var_pat (WildPat _) = True
657 var_pat (VarPat _) = True
662 mkIntegerLit :: Integer -> CoreExpr
664 | inIntRange i -- Small enough, so start from an Int
665 = mkConApp smallIntegerDataCon [mkIntLit i]
667 | otherwise -- Big, so start from a string
668 = App (Var addr2IntegerId) (Lit (MachStr (_PK_ (show i))))