2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[DsExpr]{Matching expressions (Exprs)}
7 module DsExpr ( dsExpr, dsLExpr, dsLocalBinds, dsValBinds, dsLit ) where
9 #include "HsVersions.h"
11 import Match ( matchWrapper, matchSimply, matchSinglePat )
12 import MatchLit ( dsLit, dsOverLit )
13 import DsBinds ( dsLHsBinds, dsCoercion )
14 import DsGRHSs ( dsGuarded )
15 import DsListComp ( dsListComp, dsPArrComp )
16 import DsUtils ( mkErrorAppDs, mkStringExpr, mkConsExpr, mkNilExpr,
17 extractMatchResult, cantFailMatchResult, matchCanFail,
18 mkCoreTupTy, selectSimpleMatchVarL, lookupEvidence )
19 import DsArrows ( dsProcExpr )
23 -- Template Haskell stuff iff bootstrapped
24 import DsMeta ( dsBracket )
28 import TcHsSyn ( hsPatType, mkVanillaTuplePat )
30 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
31 -- needs to see source types (newtypes etc), and sometimes not
32 -- So WATCH OUT; check each use of split*Ty functions.
33 -- Sigh. This is a pain.
35 import TcType ( tcSplitAppTy, tcSplitFunTys, tcTyConAppTyCon,
36 tcTyConAppArgs, isUnLiftedType, Type, mkAppTy )
37 import Type ( funArgTy, splitFunTys, isUnboxedTupleType, mkFunTy )
39 import CoreUtils ( exprType, mkIfThenElse, bindNonRec )
41 import CostCentre ( mkUserCC )
42 import Id ( Id, idType, idName, idDataCon )
43 import PrelInfo ( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
44 import DataCon ( DataCon, dataConWrapId, dataConFieldLabels, dataConInstOrigArgTys )
45 import DataCon ( isVanillaDataCon )
46 import TyCon ( FieldLabel, tyConDataCons )
47 import TysWiredIn ( tupleCon )
48 import BasicTypes ( RecFlag(..), Boxity(..), ipNameName )
49 import PrelNames ( toPName,
50 returnMName, bindMName, thenMName, failMName,
52 import SrcLoc ( Located(..), unLoc, getLoc, noLoc )
53 import Util ( zipEqual, zipWithEqual )
54 import Bag ( bagToList )
60 %************************************************************************
62 dsLocalBinds, dsValBinds
64 %************************************************************************
67 dsLocalBinds :: HsLocalBinds Id -> CoreExpr -> DsM CoreExpr
68 dsLocalBinds EmptyLocalBinds body = return body
69 dsLocalBinds (HsValBinds binds) body = dsValBinds binds body
70 dsLocalBinds (HsIPBinds binds) body = dsIPBinds binds body
72 -------------------------
73 dsValBinds :: HsValBinds Id -> CoreExpr -> DsM CoreExpr
74 dsValBinds (ValBindsOut binds _) body = foldrDs ds_val_bind body binds
76 -------------------------
77 dsIPBinds (IPBinds ip_binds dict_binds) body
78 = do { prs <- dsLHsBinds dict_binds
79 ; let inner = foldr (\(x,r) e -> Let (NonRec x r) e) body prs
80 ; foldrDs ds_ip_bind inner ip_binds }
82 ds_ip_bind (L _ (IPBind n e)) body
83 = dsLExpr e `thenDs` \ e' ->
84 returnDs (Let (NonRec (ipNameName n) e') body)
86 -------------------------
87 ds_val_bind :: (RecFlag, LHsBinds Id) -> CoreExpr -> DsM CoreExpr
88 -- Special case for bindings which bind unlifted variables
89 -- We need to do a case right away, rather than building
90 -- a tuple and doing selections.
91 -- Silently ignore INLINE and SPECIALISE pragmas...
92 ds_val_bind (NonRecursive, hsbinds) body
93 | [L _ (AbsBinds [] [] exports binds)] <- bagToList hsbinds,
94 (L loc bind : null_binds) <- bagToList binds,
95 or [isUnLiftedType (idType g) | (_, g, _, _) <- exports]
98 body_w_exports = foldr bind_export body exports
99 bind_export (tvs, g, l, _) body = ASSERT( null tvs )
100 bindNonRec g (Var l) body
102 ASSERT (null null_binds)
103 -- Non-recursive, non-overloaded bindings only come in ones
104 -- ToDo: in some bizarre case it's conceivable that there
105 -- could be dict binds in the 'binds'. (See the notes
106 -- below. Then pattern-match would fail. Urk.)
109 FunBind { fun_id = L _ fun, fun_matches = matches, fun_co_fn = co_fn }
110 -> matchWrapper (FunRhs (idName fun)) matches `thenDs` \ (args, rhs) ->
111 ASSERT( null args ) -- Functions aren't lifted
112 ASSERT( isIdCoercion co_fn )
113 returnDs (bindNonRec fun rhs body_w_exports)
115 PatBind {pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty }
116 -> putSrcSpanDs loc $
117 dsGuarded grhss ty `thenDs` \ rhs ->
118 mk_error_app pat `thenDs` \ error_expr ->
119 matchSimply rhs PatBindRhs pat body_w_exports error_expr
121 other -> pprPanic "dsLet: unlifted" (pprLHsBinds hsbinds $$ ppr body)
123 mk_error_app pat = mkErrorAppDs iRREFUT_PAT_ERROR_ID
127 -- Ordinary case for bindings; none should be unlifted
128 ds_val_bind (is_rec, binds) body
129 = do { prs <- dsLHsBinds binds
130 ; ASSERT( not (any (isUnLiftedType . idType . fst) prs) )
133 other -> return (Let (Rec prs) body) }
134 -- Use a Rec regardless of is_rec.
135 -- Why? Because it allows the binds to be all
136 -- mixed up, which is what happens in one rare case
137 -- Namely, for an AbsBind with no tyvars and no dicts,
138 -- but which does have dictionary bindings.
139 -- See notes with TcSimplify.inferLoop [NO TYVARS]
140 -- It turned out that wrapping a Rec here was the easiest solution
142 -- NB The previous case dealt with unlifted bindings, so we
143 -- only have to deal with lifted ones now; so Rec is ok
146 %************************************************************************
148 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
150 %************************************************************************
153 dsLExpr :: LHsExpr Id -> DsM CoreExpr
154 dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e
156 dsExpr :: HsExpr Id -> DsM CoreExpr
158 dsExpr (HsPar e) = dsLExpr e
159 dsExpr (ExprWithTySigOut e _) = dsLExpr e
160 dsExpr (HsVar var) = returnDs (Var var)
161 dsExpr (HsIPVar ip) = returnDs (Var (ipNameName ip))
162 dsExpr (HsLit lit) = dsLit lit
163 dsExpr (HsOverLit lit) = dsOverLit lit
165 dsExpr (NegApp expr neg_expr)
166 = do { core_expr <- dsLExpr expr
167 ; core_neg <- dsExpr neg_expr
168 ; return (core_neg `App` core_expr) }
170 dsExpr expr@(HsLam a_Match)
171 = matchWrapper LambdaExpr a_Match `thenDs` \ (binders, matching_code) ->
172 returnDs (mkLams binders matching_code)
174 dsExpr expr@(HsApp fun arg)
175 = dsLExpr fun `thenDs` \ core_fun ->
176 dsLExpr arg `thenDs` \ core_arg ->
177 returnDs (core_fun `App` core_arg)
180 Operator sections. At first it looks as if we can convert
189 But no! expr might be a redex, and we can lose laziness badly this
194 for example. So we convert instead to
196 let y = expr in \x -> op y x
198 If \tr{expr} is actually just a variable, say, then the simplifier
202 dsExpr (OpApp e1 op _ e2)
203 = dsLExpr op `thenDs` \ core_op ->
204 -- for the type of y, we need the type of op's 2nd argument
205 dsLExpr e1 `thenDs` \ x_core ->
206 dsLExpr e2 `thenDs` \ y_core ->
207 returnDs (mkApps core_op [x_core, y_core])
209 dsExpr (SectionL expr op)
210 = dsLExpr op `thenDs` \ core_op ->
211 -- for the type of y, we need the type of op's 2nd argument
213 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
214 -- Must look through an implicit-parameter type;
215 -- newtype impossible; hence Type.splitFunTys
217 dsLExpr expr `thenDs` \ x_core ->
218 newSysLocalDs x_ty `thenDs` \ x_id ->
219 newSysLocalDs y_ty `thenDs` \ y_id ->
221 returnDs (bindNonRec x_id x_core $
222 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
224 -- dsLExpr (SectionR op expr) -- \ x -> op x expr
225 dsExpr (SectionR op expr)
226 = dsLExpr op `thenDs` \ core_op ->
227 -- for the type of x, we need the type of op's 2nd argument
229 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
230 -- See comment with SectionL
232 dsLExpr expr `thenDs` \ y_core ->
233 newSysLocalDs x_ty `thenDs` \ x_id ->
234 newSysLocalDs y_ty `thenDs` \ y_id ->
236 returnDs (bindNonRec y_id y_core $
237 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
239 dsExpr (HsSCC cc expr)
240 = dsLExpr expr `thenDs` \ core_expr ->
241 getModuleDs `thenDs` \ mod_name ->
242 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
245 -- hdaume: core annotation
247 dsExpr (HsCoreAnn fs expr)
248 = dsLExpr expr `thenDs` \ core_expr ->
249 returnDs (Note (CoreNote $ unpackFS fs) core_expr)
251 -- Special case to handle unboxed tuple patterns; they can't appear nested
253 -- case e of (# p1, p2 #) -> rhs
255 -- case e of (# x1, x2 #) -> ... match p1, p2 ...
257 -- let x = e in case x of ....
259 -- But there may be a big
260 -- let fail = ... in case e of ...
261 -- wrapping the whole case, which complicates matters slightly
262 -- It all seems a bit fragile. Test is dsrun013.
264 dsExpr (HsCase discrim matches@(MatchGroup _ ty))
265 | isUnboxedTupleType (funArgTy ty)
266 = dsLExpr discrim `thenDs` \ core_discrim ->
267 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
269 scrungle (Case (Var x) bndr ty alts)
270 | x == discrim_var = Case core_discrim bndr ty alts
271 scrungle (Let binds body) = Let binds (scrungle body)
272 scrungle other = panic ("dsLExpr: tuple pattern:\n" ++ showSDoc (ppr other))
274 returnDs (scrungle matching_code)
276 dsExpr (HsCase discrim matches)
277 = dsLExpr discrim `thenDs` \ core_discrim ->
278 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
279 returnDs (bindNonRec discrim_var core_discrim matching_code)
281 dsExpr (HsLet binds body)
282 = dsLExpr body `thenDs` \ body' ->
283 dsLocalBinds binds body'
285 -- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
286 -- because the interpretation of `stmts' depends on what sort of thing it is.
288 dsExpr (HsDo ListComp stmts body result_ty)
289 = -- Special case for list comprehensions
290 dsListComp stmts body elt_ty
292 [elt_ty] = tcTyConAppArgs result_ty
294 dsExpr (HsDo DoExpr stmts body result_ty)
295 = dsDo stmts body result_ty
297 dsExpr (HsDo (MDoExpr tbl) stmts body result_ty)
298 = dsMDo tbl stmts body result_ty
300 dsExpr (HsDo PArrComp stmts body result_ty)
301 = -- Special case for array comprehensions
302 dsPArrComp (map unLoc stmts) body elt_ty
304 [elt_ty] = tcTyConAppArgs result_ty
306 dsExpr (HsIf guard_expr then_expr else_expr)
307 = dsLExpr guard_expr `thenDs` \ core_guard ->
308 dsLExpr then_expr `thenDs` \ core_then ->
309 dsLExpr else_expr `thenDs` \ core_else ->
310 returnDs (mkIfThenElse core_guard core_then core_else)
315 \underline{\bf Type lambda and application}
316 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
318 dsExpr (TyLam tyvars expr)
319 = dsLExpr expr `thenDs` \ core_expr ->
320 returnDs (mkLams tyvars core_expr)
322 dsExpr (TyApp expr tys)
323 = dsLExpr expr `thenDs` \ core_expr ->
324 returnDs (mkTyApps core_expr tys)
329 \underline{\bf Various data construction things}
330 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
332 dsExpr (ExplicitList ty xs)
335 go [] = returnDs (mkNilExpr ty)
336 go (x:xs) = dsLExpr x `thenDs` \ core_x ->
337 go xs `thenDs` \ core_xs ->
338 returnDs (mkConsExpr ty core_x core_xs)
340 -- we create a list from the array elements and convert them into a list using
343 -- * the main disadvantage to this scheme is that `toP' traverses the list
344 -- twice: once to determine the length and a second time to put to elements
345 -- into the array; this inefficiency could be avoided by exposing some of
346 -- the innards of `PrelPArr' to the compiler (ie, have a `PrelPArrBase') so
347 -- that we can exploit the fact that we already know the length of the array
348 -- here at compile time
350 dsExpr (ExplicitPArr ty xs)
351 = dsLookupGlobalId toPName `thenDs` \toP ->
352 dsExpr (ExplicitList ty xs) `thenDs` \coreList ->
353 returnDs (mkApps (Var toP) [Type ty, coreList])
355 dsExpr (ExplicitTuple expr_list boxity)
356 = mappM dsLExpr expr_list `thenDs` \ core_exprs ->
357 returnDs (mkConApp (tupleCon boxity (length expr_list))
358 (map (Type . exprType) core_exprs ++ core_exprs))
360 dsExpr (ArithSeq expr (From from))
361 = dsExpr expr `thenDs` \ expr2 ->
362 dsLExpr from `thenDs` \ from2 ->
363 returnDs (App expr2 from2)
365 dsExpr (ArithSeq expr (FromTo from two))
366 = dsExpr expr `thenDs` \ expr2 ->
367 dsLExpr from `thenDs` \ from2 ->
368 dsLExpr two `thenDs` \ two2 ->
369 returnDs (mkApps expr2 [from2, two2])
371 dsExpr (ArithSeq expr (FromThen from thn))
372 = dsExpr expr `thenDs` \ expr2 ->
373 dsLExpr from `thenDs` \ from2 ->
374 dsLExpr thn `thenDs` \ thn2 ->
375 returnDs (mkApps expr2 [from2, thn2])
377 dsExpr (ArithSeq expr (FromThenTo from thn two))
378 = dsExpr expr `thenDs` \ expr2 ->
379 dsLExpr from `thenDs` \ from2 ->
380 dsLExpr thn `thenDs` \ thn2 ->
381 dsLExpr two `thenDs` \ two2 ->
382 returnDs (mkApps expr2 [from2, thn2, two2])
384 dsExpr (PArrSeq expr (FromTo from two))
385 = dsExpr expr `thenDs` \ expr2 ->
386 dsLExpr from `thenDs` \ from2 ->
387 dsLExpr two `thenDs` \ two2 ->
388 returnDs (mkApps expr2 [from2, two2])
390 dsExpr (PArrSeq expr (FromThenTo from thn two))
391 = dsExpr expr `thenDs` \ expr2 ->
392 dsLExpr from `thenDs` \ from2 ->
393 dsLExpr thn `thenDs` \ thn2 ->
394 dsLExpr two `thenDs` \ two2 ->
395 returnDs (mkApps expr2 [from2, thn2, two2])
397 dsExpr (PArrSeq expr _)
398 = panic "DsExpr.dsExpr: Infinite parallel array!"
399 -- the parser shouldn't have generated it and the renamer and typechecker
400 -- shouldn't have let it through
404 \underline{\bf Record construction and update}
405 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
406 For record construction we do this (assuming T has three arguments)
410 let err = /\a -> recConErr a
411 T (recConErr t1 "M.lhs/230/op1")
413 (recConErr t1 "M.lhs/230/op3")
415 @recConErr@ then converts its arugment string into a proper message
416 before printing it as
418 M.lhs, line 230: missing field op1 was evaluated
421 We also handle @C{}@ as valid construction syntax for an unlabelled
422 constructor @C@, setting all of @C@'s fields to bottom.
425 dsExpr (RecordCon (L _ data_con_id) con_expr rbinds)
426 = dsExpr con_expr `thenDs` \ con_expr' ->
428 (arg_tys, _) = tcSplitFunTys (exprType con_expr')
429 -- A newtype in the corner should be opaque;
430 -- hence TcType.tcSplitFunTys
432 mk_arg (arg_ty, lbl) -- Selector id has the field label as its name
433 = case [rhs | (L _ sel_id, rhs) <- rbinds, lbl == idName sel_id] of
434 (rhs:rhss) -> ASSERT( null rhss )
436 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
437 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
439 labels = dataConFieldLabels (idDataCon data_con_id)
440 -- The data_con_id is guaranteed to be the wrapper id of the constructor
444 then mappM unlabelled_bottom arg_tys
445 else mappM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
446 `thenDs` \ con_args ->
448 returnDs (mkApps con_expr' con_args)
451 Record update is a little harder. Suppose we have the decl:
453 data T = T1 {op1, op2, op3 :: Int}
454 | T2 {op4, op2 :: Int}
457 Then we translate as follows:
463 T1 op1 _ op3 -> T1 op1 op2 op3
464 T2 op4 _ -> T2 op4 op2
465 other -> recUpdError "M.lhs/230"
467 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
468 RHSs, and do not generate a Core constructor application directly, because the constructor
469 might do some argument-evaluation first; and may have to throw away some
473 dsExpr (RecordUpd record_expr [] record_in_ty record_out_ty)
474 = dsLExpr record_expr
476 dsExpr expr@(RecordUpd record_expr rbinds record_in_ty record_out_ty)
477 = dsLExpr record_expr `thenDs` \ record_expr' ->
479 -- Desugar the rbinds, and generate let-bindings if
480 -- necessary so that we don't lose sharing
483 in_inst_tys = tcTyConAppArgs record_in_ty -- Newtype opaque
484 out_inst_tys = tcTyConAppArgs record_out_ty -- Newtype opaque
485 in_out_ty = mkFunTy record_in_ty record_out_ty
487 mk_val_arg field old_arg_id
488 = case [rhs | (L _ sel_id, rhs) <- rbinds, field == idName sel_id] of
489 (rhs:rest) -> ASSERT(null rest) rhs
490 [] -> nlHsVar old_arg_id
493 = newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
494 -- This call to dataConInstOrigArgTys won't work for existentials
495 -- but existentials don't have record types anyway
497 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
498 (dataConFieldLabels con) arg_ids
499 rhs = foldl (\a b -> nlHsApp a b)
500 (noLoc $ TyApp (nlHsVar (dataConWrapId con))
504 returnDs (mkSimpleMatch [noLoc $ ConPatOut (noLoc con) [] [] emptyLHsBinds
505 (PrefixCon (map nlVarPat arg_ids)) record_in_ty]
508 -- Record stuff doesn't work for existentials
509 -- The type checker checks for this, but we need
510 -- worry only about the constructors that are to be updated
511 ASSERT2( all isVanillaDataCon cons_to_upd, ppr expr )
513 -- It's important to generate the match with matchWrapper,
514 -- and the right hand sides with applications of the wrapper Id
515 -- so that everything works when we are doing fancy unboxing on the
516 -- constructor aguments.
517 mappM mk_alt cons_to_upd `thenDs` \ alts ->
518 matchWrapper RecUpd (MatchGroup alts in_out_ty) `thenDs` \ ([discrim_var], matching_code) ->
520 returnDs (bindNonRec discrim_var record_expr' matching_code)
523 updated_fields :: [FieldLabel]
524 updated_fields = [ idName sel_id | (L _ sel_id,_) <- rbinds]
526 -- Get the type constructor from the record_in_ty
527 -- so that we are sure it'll have all its DataCons
528 -- (In GHCI, it's possible that some TyCons may not have all
529 -- their constructors, in a module-loop situation.)
530 tycon = tcTyConAppTyCon record_in_ty
531 data_cons = tyConDataCons tycon
532 cons_to_upd = filter has_all_fields data_cons
534 has_all_fields :: DataCon -> Bool
535 has_all_fields con_id
536 = all (`elem` con_fields) updated_fields
538 con_fields = dataConFieldLabels con_id
543 \underline{\bf Dictionary lambda and application}
544 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
545 @DictLam@ and @DictApp@ turn into the regular old things.
546 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
547 complicated; reminiscent of fully-applied constructors.
549 dsExpr (DictLam dictvars expr)
550 = dsLExpr expr `thenDs` \ core_expr ->
551 returnDs (mkLams dictvars core_expr)
555 dsExpr (DictApp expr dicts) -- becomes a curried application
556 = dsLExpr expr `thenDs` \ core_expr ->
557 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
559 dsExpr (HsCoerce co_fn e) = dsCoercion co_fn (dsExpr e)
562 Here is where we desugar the Template Haskell brackets and escapes
565 -- Template Haskell stuff
567 #ifdef GHCI /* Only if bootstrapping */
568 dsExpr (HsBracketOut x ps) = dsBracket x ps
569 dsExpr (HsSpliceE s) = pprPanic "dsExpr:splice" (ppr s)
572 -- Arrow notation extension
573 dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
580 -- HsSyn constructs that just shouldn't be here:
581 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
586 %--------------------------------------------------------------------
588 Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
589 handled in DsListComp). Basically does the translation given in the
595 -> Type -- Type of the whole expression
598 dsDo stmts body result_ty
599 = go (map unLoc stmts)
603 go (ExprStmt rhs then_expr _ : stmts)
604 = do { rhs2 <- dsLExpr rhs
605 ; then_expr2 <- dsExpr then_expr
607 ; returnDs (mkApps then_expr2 [rhs2, rest]) }
609 go (LetStmt binds : stmts)
610 = do { rest <- go stmts
611 ; dsLocalBinds binds rest }
613 go (BindStmt pat rhs bind_op fail_op : stmts)
614 = do { body <- go stmts
615 ; var <- selectSimpleMatchVarL pat
616 ; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat
617 result_ty (cantFailMatchResult body)
618 ; match_code <- handle_failure pat match fail_op
619 ; rhs' <- dsLExpr rhs
620 ; bind_op' <- dsExpr bind_op
621 ; returnDs (mkApps bind_op' [rhs', Lam var match_code]) }
623 -- In a do expression, pattern-match failure just calls
624 -- the monadic 'fail' rather than throwing an exception
625 handle_failure pat match fail_op
627 = do { fail_op' <- dsExpr fail_op
628 ; fail_msg <- mkStringExpr (mk_fail_msg pat)
629 ; extractMatchResult match (App fail_op' fail_msg) }
631 = extractMatchResult match (error "It can't fail")
633 mk_fail_msg pat = "Pattern match failure in do expression at " ++
634 showSDoc (ppr (getLoc pat))
637 Translation for RecStmt's:
638 -----------------------------
639 We turn (RecStmt [v1,..vn] stmts) into:
641 (v1,..,vn) <- mfix (\~(v1,..vn). do stmts
648 -> Type -- Type of the whole expression
651 dsMDo tbl stmts body result_ty
652 = go (map unLoc stmts)
654 (m_ty, b_ty) = tcSplitAppTy result_ty -- result_ty must be of the form (m b)
655 mfix_id = lookupEvidence tbl mfixName
656 return_id = lookupEvidence tbl returnMName
657 bind_id = lookupEvidence tbl bindMName
658 then_id = lookupEvidence tbl thenMName
659 fail_id = lookupEvidence tbl failMName
664 go (LetStmt binds : stmts)
665 = do { rest <- go stmts
666 ; dsLocalBinds binds rest }
668 go (ExprStmt rhs _ rhs_ty : stmts)
669 = do { rhs2 <- dsLExpr rhs
671 ; returnDs (mkApps (Var then_id) [Type rhs_ty, Type b_ty, rhs2, rest]) }
673 go (BindStmt pat rhs _ _ : stmts)
674 = do { body <- go stmts
675 ; var <- selectSimpleMatchVarL pat
676 ; match <- matchSinglePat (Var var) (StmtCtxt ctxt) pat
677 result_ty (cantFailMatchResult body)
678 ; fail_msg <- mkStringExpr (mk_fail_msg pat)
679 ; let fail_expr = mkApps (Var fail_id) [Type b_ty, fail_msg]
680 ; match_code <- extractMatchResult match fail_expr
682 ; rhs' <- dsLExpr rhs
683 ; returnDs (mkApps (Var bind_id) [Type (hsPatType pat), Type b_ty,
684 rhs', Lam var match_code]) }
686 go (RecStmt rec_stmts later_ids rec_ids rec_rets binds : stmts)
687 = ASSERT( length rec_ids > 0 )
688 ASSERT( length rec_ids == length rec_rets )
689 go (new_bind_stmt : let_stmt : stmts)
691 new_bind_stmt = mkBindStmt (mk_tup_pat later_pats) mfix_app
692 let_stmt = LetStmt (HsValBinds (ValBindsOut [(Recursive, binds)] []))
695 -- Remove the later_ids that appear (without fancy coercions)
696 -- in rec_rets, because there's no need to knot-tie them separately
697 -- See Note [RecStmt] in HsExpr
698 later_ids' = filter (`notElem` mono_rec_ids) later_ids
699 mono_rec_ids = [ id | HsVar id <- rec_rets ]
701 mfix_app = nlHsApp (noLoc $ TyApp (nlHsVar mfix_id) [tup_ty]) mfix_arg
702 mfix_arg = noLoc $ HsLam (MatchGroup [mkSimpleMatch [mfix_pat] body]
703 (mkFunTy tup_ty body_ty))
705 -- The rec_tup_pat must bind the rec_ids only; remember that the
706 -- trimmed_laters may share the same Names
707 -- Meanwhile, the later_pats must bind the later_vars
708 rec_tup_pats = map mk_wild_pat later_ids' ++ map nlVarPat rec_ids
709 later_pats = map nlVarPat later_ids' ++ map mk_later_pat rec_ids
710 rets = map nlHsVar later_ids' ++ map noLoc rec_rets
712 mfix_pat = noLoc $ LazyPat $ mk_tup_pat rec_tup_pats
713 body = noLoc $ HsDo ctxt rec_stmts return_app body_ty
714 body_ty = mkAppTy m_ty tup_ty
715 tup_ty = mkCoreTupTy (map idType (later_ids' ++ rec_ids))
716 -- mkCoreTupTy deals with singleton case
718 return_app = nlHsApp (noLoc $ TyApp (nlHsVar return_id) [tup_ty])
721 mk_wild_pat :: Id -> LPat Id
722 mk_wild_pat v = noLoc $ WildPat $ idType v
724 mk_later_pat :: Id -> LPat Id
725 mk_later_pat v | v `elem` later_ids' = mk_wild_pat v
726 | otherwise = nlVarPat v
728 mk_tup_pat :: [LPat Id] -> LPat Id
730 mk_tup_pat ps = noLoc $ mkVanillaTuplePat ps Boxed
732 mk_ret_tup :: [LHsExpr Id] -> LHsExpr Id
734 mk_ret_tup rs = noLoc $ ExplicitTuple rs Boxed