2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[DsExpr]{Matching expressions (Exprs)}
7 module DsExpr ( dsExpr, dsLExpr, dsLet, dsLit ) where
9 #include "HsVersions.h"
12 import Match ( matchWrapper, matchSimply )
13 import MatchLit ( dsLit )
14 import DsBinds ( dsHsNestedBinds )
15 import DsGRHSs ( dsGuarded )
16 import DsListComp ( dsListComp, dsPArrComp )
17 import DsUtils ( mkErrorAppDs, mkStringExpr, mkConsExpr, mkNilExpr,
18 mkCoreTupTy, selectSimpleMatchVarL,
19 dsReboundNames, lookupReboundName )
20 import DsArrows ( dsProcExpr )
24 -- Template Haskell stuff iff bootstrapped
25 import DsMeta ( dsBracket )
29 import TcHsSyn ( hsPatType )
31 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
32 -- needs to see source types (newtypes etc), and sometimes not
33 -- So WATCH OUT; check each use of split*Ty functions.
34 -- Sigh. This is a pain.
36 import TcType ( tcSplitAppTy, tcSplitFunTys, tcTyConAppTyCon, tcTyConAppArgs,
37 tcTyConAppArgs, isUnLiftedType, Type, mkAppTy, tcEqType )
38 import Type ( funArgTy, splitFunTys, isUnboxedTupleType, mkFunTy )
40 import CoreUtils ( exprType, mkIfThenElse, bindNonRec )
42 import CostCentre ( mkUserCC )
43 import Id ( Id, idType, idName )
44 import PrelInfo ( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
45 import DataCon ( DataCon, dataConWrapId, dataConFieldLabels, dataConInstOrigArgTys )
46 import DataCon ( isVanillaDataCon )
48 import TyCon ( FieldLabel, tyConDataCons )
49 import TysWiredIn ( tupleCon )
50 import BasicTypes ( RecFlag(..), Boxity(..), ipNameName )
51 import PrelNames ( toPName,
52 returnMName, bindMName, thenMName, failMName,
54 import SrcLoc ( Located(..), unLoc, getLoc, noLoc )
55 import Util ( zipEqual, zipWithEqual )
56 import Bag ( bagToList )
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 :: [HsBindGroup Id] -> CoreExpr -> DsM CoreExpr
81 dsLet groups body = foldlDs dsBindGroup body (reverse groups)
83 dsBindGroup :: CoreExpr -> HsBindGroup Id -> DsM CoreExpr
84 dsBindGroup body (HsIPBinds binds)
85 = foldlDs dsIPBind body binds
87 dsIPBind body (L _ (IPBind n e))
88 = dsLExpr e `thenDs` \ e' ->
89 returnDs (Let (NonRec (ipNameName n) e') body)
91 -- Special case for bindings which bind unlifted variables
92 -- We need to do a case right away, rather than building
93 -- a tuple and doing selections.
94 -- Silently ignore INLINE pragmas...
95 dsBindGroup body bind@(HsBindGroup hsbinds sigs is_rec)
96 | [L _ (AbsBinds [] [] exports inlines binds)] <- bagToList hsbinds,
97 or [isUnLiftedType (idType g) | (_, g, l) <- exports]
98 = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
99 -- Unlifted bindings are always non-recursive
100 -- and are always a Fun or Pat monobind
102 -- ToDo: in some bizarre case it's conceivable that there
103 -- could be dict binds in the 'binds'. (See the notes
104 -- below. Then pattern-match would fail. Urk.)
106 body_w_exports = foldr bind_export body exports
107 bind_export (tvs, g, l) body = ASSERT( null tvs )
108 bindNonRec g (Var l) body
110 mk_error_app pat = mkErrorAppDs iRREFUT_PAT_ERROR_ID
114 case bagToList binds of
115 [L loc (FunBind (L _ fun) _ matches)]
116 -> putSrcSpanDs loc $
117 matchWrapper (FunRhs (idName fun)) matches `thenDs` \ (args, rhs) ->
118 ASSERT( null args ) -- Functions aren't lifted
119 returnDs (bindNonRec fun rhs body_w_exports)
121 [L loc (PatBind pat grhss ty)]
122 -> putSrcSpanDs loc $
123 dsGuarded grhss ty `thenDs` \ rhs ->
124 mk_error_app pat `thenDs` \ error_expr ->
125 matchSimply rhs PatBindRhs pat body_w_exports error_expr
127 other -> pprPanic "dsLet: unlifted" (ppr bind $$ ppr body)
129 -- Ordinary case for bindings
130 dsBindGroup body (HsBindGroup binds sigs is_rec)
131 = dsHsNestedBinds binds `thenDs` \ prs ->
132 returnDs (Let (Rec prs) body)
133 -- Use a Rec regardless of is_rec.
134 -- Why? Because it allows the binds to be all
135 -- mixed up, which is what happens in one rare case
136 -- Namely, for an AbsBind with no tyvars and no dicts,
137 -- but which does have dictionary bindings.
138 -- See notes with TcSimplify.inferLoop [NO TYVARS]
139 -- It turned out that wrapping a Rec here was the easiest solution
141 -- NB The previous case dealt with unlifted bindings, so we
142 -- only have to deal with lifted ones now; so Rec is ok
145 %************************************************************************
147 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
149 %************************************************************************
152 dsLExpr :: LHsExpr Id -> DsM CoreExpr
153 dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e
155 dsExpr :: HsExpr Id -> DsM CoreExpr
157 dsExpr (HsPar e) = dsLExpr e
158 dsExpr (ExprWithTySigOut e _) = dsLExpr e
159 dsExpr (HsVar var) = returnDs (Var var)
160 dsExpr (HsIPVar ip) = returnDs (Var (ipNameName ip))
161 dsExpr (HsLit lit) = dsLit lit
162 -- HsOverLit has been gotten rid of by the type checker
164 dsExpr expr@(HsLam a_Match)
165 = matchWrapper LambdaExpr a_Match `thenDs` \ (binders, matching_code) ->
166 returnDs (mkLams binders matching_code)
168 dsExpr expr@(HsApp fun arg)
169 = dsLExpr fun `thenDs` \ core_fun ->
170 dsLExpr arg `thenDs` \ core_arg ->
171 returnDs (core_fun `App` core_arg)
174 Operator sections. At first it looks as if we can convert
183 But no! expr might be a redex, and we can lose laziness badly this
188 for example. So we convert instead to
190 let y = expr in \x -> op y x
192 If \tr{expr} is actually just a variable, say, then the simplifier
196 dsExpr (OpApp e1 op _ e2)
197 = dsLExpr op `thenDs` \ core_op ->
198 -- for the type of y, we need the type of op's 2nd argument
199 dsLExpr e1 `thenDs` \ x_core ->
200 dsLExpr e2 `thenDs` \ y_core ->
201 returnDs (mkApps core_op [x_core, y_core])
203 dsExpr (SectionL expr op)
204 = dsLExpr op `thenDs` \ core_op ->
205 -- for the type of y, we need the type of op's 2nd argument
207 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
208 -- Must look through an implicit-parameter type;
209 -- newtype impossible; hence Type.splitFunTys
211 dsLExpr expr `thenDs` \ x_core ->
212 newSysLocalDs x_ty `thenDs` \ x_id ->
213 newSysLocalDs y_ty `thenDs` \ y_id ->
215 returnDs (bindNonRec x_id x_core $
216 Lam y_id (mkApps core_op [Var x_id, Var y_id]))
218 -- dsLExpr (SectionR op expr) -- \ x -> op x expr
219 dsExpr (SectionR op expr)
220 = dsLExpr op `thenDs` \ core_op ->
221 -- for the type of x, we need the type of op's 2nd argument
223 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
224 -- See comment with SectionL
226 dsLExpr expr `thenDs` \ y_core ->
227 newSysLocalDs x_ty `thenDs` \ x_id ->
228 newSysLocalDs y_ty `thenDs` \ y_id ->
230 returnDs (bindNonRec y_id y_core $
231 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
233 dsExpr (HsSCC cc expr)
234 = dsLExpr expr `thenDs` \ core_expr ->
235 getModuleDs `thenDs` \ mod_name ->
236 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
239 -- hdaume: core annotation
241 dsExpr (HsCoreAnn fs expr)
242 = dsLExpr expr `thenDs` \ core_expr ->
243 returnDs (Note (CoreNote $ unpackFS fs) core_expr)
245 -- Special case to handle unboxed tuple patterns; they can't appear nested
246 dsExpr (HsCase discrim matches@(MatchGroup _ ty))
247 | isUnboxedTupleType (funArgTy ty)
248 = dsLExpr discrim `thenDs` \ core_discrim ->
249 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
250 case matching_code of
251 Case (Var x) bndr ty alts | x == discrim_var ->
252 returnDs (Case core_discrim bndr ty alts)
253 _ -> panic ("dsLExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
255 dsExpr (HsCase discrim matches)
256 = dsLExpr discrim `thenDs` \ core_discrim ->
257 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
258 returnDs (bindNonRec discrim_var core_discrim matching_code)
260 dsExpr (HsLet binds body)
261 = dsLExpr body `thenDs` \ body' ->
264 -- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
265 -- because the interpretation of `stmts' depends on what sort of thing it is.
267 dsExpr (HsDo ListComp stmts _ result_ty)
268 = -- Special case for list comprehensions
269 dsListComp stmts elt_ty
271 [elt_ty] = tcTyConAppArgs result_ty
273 dsExpr (HsDo do_or_lc stmts ids result_ty)
275 = dsDo do_or_lc stmts ids result_ty
277 dsExpr (HsDo PArrComp stmts _ result_ty)
278 = -- Special case for array comprehensions
279 dsPArrComp (map unLoc stmts) elt_ty
281 [elt_ty] = tcTyConAppArgs result_ty
283 dsExpr (HsIf guard_expr then_expr else_expr)
284 = dsLExpr guard_expr `thenDs` \ core_guard ->
285 dsLExpr then_expr `thenDs` \ core_then ->
286 dsLExpr else_expr `thenDs` \ core_else ->
287 returnDs (mkIfThenElse core_guard core_then core_else)
292 \underline{\bf Type lambda and application}
293 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~
295 dsExpr (TyLam tyvars expr)
296 = dsLExpr expr `thenDs` \ core_expr ->
297 returnDs (mkLams tyvars core_expr)
299 dsExpr (TyApp expr tys)
300 = dsLExpr expr `thenDs` \ core_expr ->
301 returnDs (mkTyApps core_expr tys)
306 \underline{\bf Various data construction things}
307 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
309 dsExpr (ExplicitList ty xs)
312 go [] = returnDs (mkNilExpr ty)
313 go (x:xs) = dsLExpr x `thenDs` \ core_x ->
314 go xs `thenDs` \ core_xs ->
315 returnDs (mkConsExpr ty core_x core_xs)
317 -- we create a list from the array elements and convert them into a list using
320 -- * the main disadvantage to this scheme is that `toP' traverses the list
321 -- twice: once to determine the length and a second time to put to elements
322 -- into the array; this inefficiency could be avoided by exposing some of
323 -- the innards of `PrelPArr' to the compiler (ie, have a `PrelPArrBase') so
324 -- that we can exploit the fact that we already know the length of the array
325 -- here at compile time
327 dsExpr (ExplicitPArr ty xs)
328 = dsLookupGlobalId toPName `thenDs` \toP ->
329 dsExpr (ExplicitList ty xs) `thenDs` \coreList ->
330 returnDs (mkApps (Var toP) [Type ty, coreList])
332 dsExpr (ExplicitTuple expr_list boxity)
333 = mappM dsLExpr expr_list `thenDs` \ core_exprs ->
334 returnDs (mkConApp (tupleCon boxity (length expr_list))
335 (map (Type . exprType) core_exprs ++ core_exprs))
337 dsExpr (ArithSeqOut expr (From from))
338 = dsLExpr expr `thenDs` \ expr2 ->
339 dsLExpr from `thenDs` \ from2 ->
340 returnDs (App expr2 from2)
342 dsExpr (ArithSeqOut expr (FromTo from two))
343 = dsLExpr expr `thenDs` \ expr2 ->
344 dsLExpr from `thenDs` \ from2 ->
345 dsLExpr two `thenDs` \ two2 ->
346 returnDs (mkApps expr2 [from2, two2])
348 dsExpr (ArithSeqOut expr (FromThen from thn))
349 = dsLExpr expr `thenDs` \ expr2 ->
350 dsLExpr from `thenDs` \ from2 ->
351 dsLExpr thn `thenDs` \ thn2 ->
352 returnDs (mkApps expr2 [from2, thn2])
354 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
355 = dsLExpr expr `thenDs` \ expr2 ->
356 dsLExpr from `thenDs` \ from2 ->
357 dsLExpr thn `thenDs` \ thn2 ->
358 dsLExpr two `thenDs` \ two2 ->
359 returnDs (mkApps expr2 [from2, thn2, two2])
361 dsExpr (PArrSeqOut expr (FromTo from two))
362 = dsLExpr expr `thenDs` \ expr2 ->
363 dsLExpr from `thenDs` \ from2 ->
364 dsLExpr two `thenDs` \ two2 ->
365 returnDs (mkApps expr2 [from2, two2])
367 dsExpr (PArrSeqOut expr (FromThenTo from thn two))
368 = dsLExpr expr `thenDs` \ expr2 ->
369 dsLExpr from `thenDs` \ from2 ->
370 dsLExpr thn `thenDs` \ thn2 ->
371 dsLExpr two `thenDs` \ two2 ->
372 returnDs (mkApps expr2 [from2, thn2, two2])
374 dsExpr (PArrSeqOut expr _)
375 = panic "DsExpr.dsExpr: Infinite parallel array!"
376 -- the parser shouldn't have generated it and the renamer and typechecker
377 -- shouldn't have let it through
381 \underline{\bf Record construction and update}
382 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
383 For record construction we do this (assuming T has three arguments)
387 let err = /\a -> recConErr a
388 T (recConErr t1 "M.lhs/230/op1")
390 (recConErr t1 "M.lhs/230/op3")
392 @recConErr@ then converts its arugment string into a proper message
393 before printing it as
395 M.lhs, line 230: missing field op1 was evaluated
398 We also handle @C{}@ as valid construction syntax for an unlabelled
399 constructor @C@, setting all of @C@'s fields to bottom.
402 dsExpr (RecordConOut data_con con_expr rbinds)
403 = dsLExpr con_expr `thenDs` \ con_expr' ->
405 (arg_tys, _) = tcSplitFunTys (exprType con_expr')
406 -- A newtype in the corner should be opaque;
407 -- hence TcType.tcSplitFunTys
409 mk_arg (arg_ty, lbl) -- Selector id has the field label as its name
410 = case [rhs | (L _ sel_id, rhs) <- rbinds, lbl == idName sel_id] of
411 (rhs:rhss) -> ASSERT( null rhss )
413 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
414 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
416 labels = dataConFieldLabels data_con
420 then mappM unlabelled_bottom arg_tys
421 else mappM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
422 `thenDs` \ con_args ->
424 returnDs (mkApps con_expr' con_args)
427 Record update is a little harder. Suppose we have the decl:
429 data T = T1 {op1, op2, op3 :: Int}
430 | T2 {op4, op2 :: Int}
433 Then we translate as follows:
439 T1 op1 _ op3 -> T1 op1 op2 op3
440 T2 op4 _ -> T2 op4 op2
441 other -> recUpdError "M.lhs/230"
443 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
444 RHSs, and do not generate a Core constructor application directly, because the constructor
445 might do some argument-evaluation first; and may have to throw away some
449 dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty [])
450 = dsLExpr record_expr
452 dsExpr expr@(RecordUpdOut record_expr record_in_ty record_out_ty rbinds)
453 = dsLExpr record_expr `thenDs` \ record_expr' ->
455 -- Desugar the rbinds, and generate let-bindings if
456 -- necessary so that we don't lose sharing
459 in_inst_tys = tcTyConAppArgs record_in_ty -- Newtype opaque
460 out_inst_tys = tcTyConAppArgs record_out_ty -- Newtype opaque
461 in_out_ty = mkFunTy record_in_ty record_out_ty
463 mk_val_arg field old_arg_id
464 = case [rhs | (L _ sel_id, rhs) <- rbinds, field == idName sel_id] of
465 (rhs:rest) -> ASSERT(null rest) rhs
466 [] -> nlHsVar old_arg_id
469 = newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
470 -- This call to dataConArgTys won't work for existentials
471 -- but existentials don't have record types anyway
473 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
474 (dataConFieldLabels con) arg_ids
475 rhs = foldl (\a b -> nlHsApp a b)
476 (noLoc $ TyApp (nlHsVar (dataConWrapId con))
480 returnDs (mkSimpleMatch [noLoc $ ConPatOut (noLoc con) [] [] emptyLHsBinds
481 (PrefixCon (map nlVarPat arg_ids)) record_in_ty]
484 -- Record stuff doesn't work for existentials
485 -- The type checker checks for this, but we need
486 -- worry only about the constructors that are to be updated
487 ASSERT2( all isVanillaDataCon cons_to_upd, ppr expr )
489 -- It's important to generate the match with matchWrapper,
490 -- and the right hand sides with applications of the wrapper Id
491 -- so that everything works when we are doing fancy unboxing on the
492 -- constructor aguments.
493 mappM mk_alt cons_to_upd `thenDs` \ alts ->
494 matchWrapper RecUpd (MatchGroup alts in_out_ty) `thenDs` \ ([discrim_var], matching_code) ->
496 returnDs (bindNonRec discrim_var record_expr' matching_code)
499 updated_fields :: [FieldLabel]
500 updated_fields = [ idName sel_id | (L _ sel_id,_) <- rbinds]
502 -- Get the type constructor from the record_in_ty
503 -- so that we are sure it'll have all its DataCons
504 -- (In GHCI, it's possible that some TyCons may not have all
505 -- their constructors, in a module-loop situation.)
506 tycon = tcTyConAppTyCon record_in_ty
507 data_cons = tyConDataCons tycon
508 cons_to_upd = filter has_all_fields data_cons
510 has_all_fields :: DataCon -> Bool
511 has_all_fields con_id
512 = all (`elem` con_fields) updated_fields
514 con_fields = dataConFieldLabels con_id
519 \underline{\bf Dictionary lambda and application}
520 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
521 @DictLam@ and @DictApp@ turn into the regular old things.
522 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
523 complicated; reminiscent of fully-applied constructors.
525 dsExpr (DictLam dictvars expr)
526 = dsLExpr expr `thenDs` \ core_expr ->
527 returnDs (mkLams dictvars core_expr)
531 dsExpr (DictApp expr dicts) -- becomes a curried application
532 = dsLExpr expr `thenDs` \ core_expr ->
533 returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
536 Here is where we desugar the Template Haskell brackets and escapes
539 -- Template Haskell stuff
541 #ifdef GHCI /* Only if bootstrapping */
542 dsExpr (HsBracketOut x ps) = dsBracket x ps
543 dsExpr (HsSpliceE s) = pprPanic "dsExpr:splice" (ppr s)
546 -- Arrow notation extension
547 dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
554 -- HsSyn constructs that just shouldn't be here:
555 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
556 dsExpr (ArithSeqIn _) = panic "dsExpr:ArithSeqIn"
557 dsExpr (PArrSeqIn _) = panic "dsExpr:PArrSeqIn"
562 %--------------------------------------------------------------------
564 Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
565 handled in DsListComp). Basically does the translation given in the
569 dsDo :: HsStmtContext Name
571 -> ReboundNames Id -- id for: [return,fail,>>=,>>] and possibly mfixName
572 -> Type -- Element type; the whole expression has type (m t)
575 dsDo do_or_lc stmts ids result_ty
576 = dsReboundNames ids `thenDs` \ (meth_binds, ds_meths) ->
578 fail_id = lookupReboundName ds_meths failMName
579 bind_id = lookupReboundName ds_meths bindMName
580 then_id = lookupReboundName ds_meths thenMName
582 (m_ty, b_ty) = tcSplitAppTy result_ty -- result_ty must be of the form (m b)
584 -- For ExprStmt, see the comments near HsExpr.Stmt about
585 -- exactly what ExprStmts mean!
587 -- In dsDo we can only see DoStmt and ListComp (no guards)
589 go [ResultStmt expr] = dsLExpr expr
592 go (ExprStmt expr a_ty : stmts)
593 = dsLExpr expr `thenDs` \ expr2 ->
594 go stmts `thenDs` \ rest ->
595 returnDs (mkApps then_id [Type a_ty, Type b_ty, expr2, rest])
597 go (LetStmt binds : stmts)
598 = go stmts `thenDs` \ rest ->
601 go (BindStmt pat expr : stmts)
602 = go stmts `thenDs` \ body ->
603 dsLExpr expr `thenDs` \ rhs ->
604 mkStringExpr (mk_msg (getLoc pat)) `thenDs` \ core_msg ->
606 -- In a do expression, pattern-match failure just calls
607 -- the monadic 'fail' rather than throwing an exception
608 fail_expr = mkApps fail_id [Type b_ty, core_msg]
611 selectSimpleMatchVarL pat `thenDs` \ var ->
612 matchSimply (Var var) (StmtCtxt do_or_lc) pat
613 body fail_expr `thenDs` \ match_code ->
614 returnDs (mkApps bind_id [Type a_ty, Type b_ty, rhs, Lam var match_code])
616 go (RecStmt rec_stmts later_vars rec_vars rec_rets : stmts)
617 = go (bind_stmt : stmts)
619 bind_stmt = dsRecStmt m_ty ds_meths rec_stmts later_vars rec_vars rec_rets
622 go (map unLoc stmts) `thenDs` \ stmts_code ->
623 returnDs (foldr Let stmts_code meth_binds)
626 mk_msg locn = "Pattern match failure in do expression at " ++ showSDoc (ppr locn)
629 Translation for RecStmt's:
630 -----------------------------
631 We turn (RecStmt [v1,..vn] stmts) into:
633 (v1,..,vn) <- mfix (\~(v1,..vn). do stmts
637 dsRecStmt :: Type -- Monad type constructor :: * -> *
638 -> [(Name,Id)] -- Rebound Ids
640 -> [Id] -> [Id] -> [LHsExpr Id]
642 dsRecStmt m_ty ds_meths stmts later_vars rec_vars rec_rets
643 = ASSERT( length rec_vars > 0 )
644 ASSERT( length rec_vars == length rec_rets )
645 BindStmt (mk_tup_pat later_pats) mfix_app
647 -- Remove any vars from later_vars that already in rec_vars
648 -- NB that having the same name is not enough; they must have
649 -- the same type. See Note [RecStmt] in HsExpr.
650 trimmed_laters = filter not_in_rec later_vars
651 not_in_rec lv = null [ v | let lv_type = idType lv
654 , lv_type `tcEqType` idType v ]
656 mfix_app = nlHsApp (noLoc $ TyApp (nlHsVar mfix_id) [tup_ty]) mfix_arg
657 mfix_arg = noLoc $ HsLam (MatchGroup [mkSimpleMatch [mfix_pat] body]
658 (mkFunTy tup_ty body_ty))
660 -- The rec_tup_pat must bind the rec_vars only; remember that the
661 -- trimmed_laters may share the same Names
662 -- Meanwhile, the later_pats must bind the later_vars
663 rec_tup_pats = map mk_wild_pat trimmed_laters ++ map nlVarPat rec_vars
664 later_pats = map nlVarPat trimmed_laters ++ map mk_later_pat rec_vars
665 rets = map nlHsVar trimmed_laters ++ rec_rets
667 mfix_pat = noLoc $ LazyPat $ mk_tup_pat rec_tup_pats
668 body = noLoc $ HsDo DoExpr (stmts ++ [return_stmt])
669 [(n, HsVar id) | (n,id) <- ds_meths] -- A bit of a hack
671 body_ty = mkAppTy m_ty tup_ty
672 tup_ty = mkCoreTupTy (map idType (trimmed_laters ++ rec_vars))
673 -- mkCoreTupTy deals with singleton case
675 Var return_id = lookupReboundName ds_meths returnMName
676 Var mfix_id = lookupReboundName ds_meths mfixName
678 return_stmt = noLoc $ ResultStmt return_app
679 return_app = nlHsApp (noLoc $ TyApp (nlHsVar return_id) [tup_ty])
682 mk_wild_pat :: Id -> LPat Id
683 mk_wild_pat v = noLoc $ WildPat $ idType v
685 mk_later_pat :: Id -> LPat Id
686 mk_later_pat v | v `elem` trimmed_laters = mk_wild_pat v
687 | otherwise = nlVarPat v
689 mk_tup_pat :: [LPat Id] -> LPat Id
691 mk_tup_pat ps = noLoc $ TuplePat ps Boxed
693 mk_ret_tup :: [LHsExpr Id] -> LHsExpr Id
695 mk_ret_tup rs = noLoc $ ExplicitTuple rs Boxed