2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Desugaring exporessions.
9 module DsExpr ( dsExpr, dsLExpr, dsLocalBinds, dsValBinds, dsLit ) where
11 #include "HsVersions.h"
26 -- Template Haskell stuff iff bootstrapped
35 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
36 -- needs to see source types
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 = Let (Rec prs) body
80 -- The dict bindings may not be in
81 -- dependency order; hence Rec
82 ; foldrDs ds_ip_bind inner ip_binds }
84 ds_ip_bind (L _ (IPBind n e)) body
85 = dsLExpr e `thenDs` \ e' ->
86 returnDs (Let (NonRec (ipNameName n) e') body)
88 -------------------------
89 ds_val_bind :: (RecFlag, LHsBinds Id) -> CoreExpr -> DsM CoreExpr
90 -- Special case for bindings which bind unlifted variables
91 -- We need to do a case right away, rather than building
92 -- a tuple and doing selections.
93 -- Silently ignore INLINE and SPECIALISE pragmas...
94 ds_val_bind (NonRecursive, hsbinds) body
95 | [L _ (AbsBinds [] [] exports binds)] <- bagToList hsbinds,
96 (L loc bind : null_binds) <- bagToList binds,
98 || isUnboxedTupleBind bind
99 || or [isUnLiftedType (idType g) | (_, g, _, _) <- exports]
101 body_w_exports = foldr bind_export body exports
102 bind_export (tvs, g, l, _) body = ASSERT( null tvs )
103 bindNonRec g (Var l) body
105 ASSERT (null null_binds)
106 -- Non-recursive, non-overloaded bindings only come in ones
107 -- ToDo: in some bizarre case it's conceivable that there
108 -- could be dict binds in the 'binds'. (See the notes
109 -- below. Then pattern-match would fail. Urk.)
112 FunBind { fun_id = L _ fun, fun_matches = matches, fun_co_fn = co_fn, fun_tick = tick }
113 -> matchWrapper (FunRhs (idName fun)) matches `thenDs` \ (args, rhs) ->
114 ASSERT( null args ) -- Functions aren't lifted
115 ASSERT( isIdHsWrapper co_fn )
116 mkOptTickBox tick rhs `thenDs` \ rhs' ->
117 returnDs (bindNonRec fun rhs' body_w_exports)
119 PatBind {pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty }
120 -> -- let C x# y# = rhs in body
121 -- ==> case rhs of C x# y# -> body
123 do { rhs <- dsGuarded grhss ty
124 ; let upat = unLoc pat
125 eqn = EqnInfo { eqn_pats = [upat],
126 eqn_rhs = cantFailMatchResult body_w_exports }
127 ; var <- selectMatchVar upat
128 ; result <- matchEquations PatBindRhs [var] [eqn] (exprType body)
129 ; return (scrungleMatch var rhs result) }
131 other -> pprPanic "dsLet: unlifted" (pprLHsBinds hsbinds $$ ppr body)
134 -- Ordinary case for bindings; none should be unlifted
135 ds_val_bind (is_rec, binds) body
136 = do { prs <- dsLHsBinds binds
137 ; ASSERT( not (any (isUnLiftedType . idType . fst) prs) )
140 other -> return (Let (Rec prs) body) }
141 -- Use a Rec regardless of is_rec.
142 -- Why? Because it allows the binds to be all
143 -- mixed up, which is what happens in one rare case
144 -- Namely, for an AbsBind with no tyvars and no dicts,
145 -- but which does have dictionary bindings.
146 -- See notes with TcSimplify.inferLoop [NO TYVARS]
147 -- It turned out that wrapping a Rec here was the easiest solution
149 -- NB The previous case dealt with unlifted bindings, so we
150 -- only have to deal with lifted ones now; so Rec is ok
152 isUnboxedTupleBind :: HsBind Id -> Bool
153 isUnboxedTupleBind (PatBind { pat_rhs_ty = ty }) = isUnboxedTupleType ty
154 isUnboxedTupleBind other = False
156 scrungleMatch :: Id -> CoreExpr -> CoreExpr -> CoreExpr
157 -- Returns something like (let var = scrut in body)
158 -- but if var is an unboxed-tuple type, it inlines it in a fragile way
159 -- Special case to handle unboxed tuple patterns; they can't appear nested
161 -- case e of (# p1, p2 #) -> rhs
163 -- case e of (# x1, x2 #) -> ... match p1, p2 ...
165 -- let x = e in case x of ....
167 -- But there may be a big
168 -- let fail = ... in case e of ...
169 -- wrapping the whole case, which complicates matters slightly
170 -- It all seems a bit fragile. Test is dsrun013.
172 scrungleMatch var scrut body
173 | isUnboxedTupleType (idType var) = scrungle body
174 | otherwise = bindNonRec var scrut body
176 scrungle (Case (Var x) bndr ty alts)
177 | x == var = Case scrut bndr ty alts
178 scrungle (Let binds body) = Let binds (scrungle body)
179 scrungle other = panic ("scrungleMatch: tuple pattern:\n" ++ showSDoc (ppr other))
183 %************************************************************************
185 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
187 %************************************************************************
190 dsLExpr :: LHsExpr Id -> DsM CoreExpr
193 dsLExpr (L loc expr@(HsWrap w (HsVar v)))
194 | idName v `elem` [breakpointName, breakpointCondName, breakpointAutoName]
195 = do areBreakpointsEnabled <- breakpoints_enabled
196 if areBreakpointsEnabled
198 L _ breakpointExpr <- mkBreakpointExpr loc v
199 dsLExpr (L loc $ HsWrap w breakpointExpr)
200 else putSrcSpanDs loc $ dsExpr expr
203 dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e
205 dsExpr :: HsExpr Id -> DsM CoreExpr
206 dsExpr (HsPar e) = dsLExpr e
207 dsExpr (ExprWithTySigOut e _) = dsLExpr e
208 dsExpr (HsVar var) = returnDs (Var var)
209 dsExpr (HsIPVar ip) = returnDs (Var (ipNameName ip))
210 dsExpr (HsLit lit) = dsLit lit
211 dsExpr (HsOverLit lit) = dsOverLit lit
212 dsExpr (HsWrap co_fn e) = dsCoercion co_fn (dsExpr e)
214 dsExpr (NegApp expr neg_expr)
215 = do { core_expr <- dsLExpr expr
216 ; core_neg <- dsExpr neg_expr
217 ; return (core_neg `App` core_expr) }
219 dsExpr expr@(HsLam a_Match)
220 = matchWrapper LambdaExpr a_Match `thenDs` \ (binders, matching_code) ->
221 returnDs (mkLams binders matching_code)
223 dsExpr expr@(HsApp fun arg)
224 = dsLExpr fun `thenDs` \ core_fun ->
225 dsLExpr arg `thenDs` \ core_arg ->
226 returnDs (core_fun `App` core_arg)
229 Operator sections. At first it looks as if we can convert
238 But no! expr might be a redex, and we can lose laziness badly this
243 for example. So we convert instead to
245 let y = expr in \x -> op y x
247 If \tr{expr} is actually just a variable, say, then the simplifier
251 dsExpr (OpApp e1 op _ e2)
252 = dsLExpr op `thenDs` \ core_op ->
253 -- for the type of y, we need the type of op's 2nd argument
254 dsLExpr e1 `thenDs` \ x_core ->
255 dsLExpr e2 `thenDs` \ y_core ->
256 returnDs (mkApps core_op [x_core, y_core])
258 dsExpr (SectionL expr op) -- Desugar (e !) to ((!) e)
259 = dsLExpr op `thenDs` \ core_op ->
260 dsLExpr expr `thenDs` \ x_core ->
261 returnDs (App core_op x_core)
263 -- dsLExpr (SectionR op expr) -- \ x -> op x expr
264 dsExpr (SectionR op expr)
265 = dsLExpr op `thenDs` \ core_op ->
266 -- for the type of x, we need the type of op's 2nd argument
268 (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
269 -- See comment with SectionL
271 dsLExpr expr `thenDs` \ y_core ->
272 newSysLocalDs x_ty `thenDs` \ x_id ->
273 newSysLocalDs y_ty `thenDs` \ y_id ->
275 returnDs (bindNonRec y_id y_core $
276 Lam x_id (mkApps core_op [Var x_id, Var y_id]))
278 dsExpr (HsSCC cc expr)
279 = dsLExpr expr `thenDs` \ core_expr ->
280 getModuleDs `thenDs` \ mod_name ->
281 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
284 -- hdaume: core annotation
286 dsExpr (HsCoreAnn fs expr)
287 = dsLExpr expr `thenDs` \ core_expr ->
288 returnDs (Note (CoreNote $ unpackFS fs) core_expr)
290 dsExpr (HsCase discrim matches)
291 = dsLExpr discrim `thenDs` \ core_discrim ->
292 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
293 returnDs (scrungleMatch discrim_var core_discrim matching_code)
295 -- Pepe: The binds are in scope in the body but NOT in the binding group
296 -- This is to avoid silliness in breakpoints
297 dsExpr (HsLet binds body)
298 = (bindLocalsDs (map unLoc $ collectLocalBinders binds) $
299 dsAndThenMaybeInsertBreakpoint body) `thenDs` \ body' ->
300 dsLocalBinds binds body'
302 -- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
303 -- because the interpretation of `stmts' depends on what sort of thing it is.
305 dsExpr (HsDo ListComp stmts body result_ty)
306 = -- Special case for list comprehensions
307 dsListComp stmts body elt_ty
309 [elt_ty] = tcTyConAppArgs result_ty
311 dsExpr (HsDo DoExpr stmts body result_ty)
312 = dsDo stmts body result_ty
314 dsExpr (HsDo (MDoExpr tbl) stmts body result_ty)
315 = dsMDo tbl stmts body result_ty
317 dsExpr (HsDo PArrComp stmts body result_ty)
318 = -- Special case for array comprehensions
319 dsPArrComp (map unLoc stmts) body elt_ty
321 [elt_ty] = tcTyConAppArgs result_ty
323 dsExpr (HsIf guard_expr then_expr else_expr)
324 = dsLExpr guard_expr `thenDs` \ core_guard ->
325 dsLExpr then_expr `thenDs` \ core_then ->
326 dsLExpr else_expr `thenDs` \ core_else ->
327 returnDs (mkIfThenElse core_guard core_then core_else)
332 \underline{\bf Various data construction things}
333 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
335 dsExpr (ExplicitList ty xs)
338 go [] = returnDs (mkNilExpr ty)
339 go (x:xs) = dsLExpr x `thenDs` \ core_x ->
340 go xs `thenDs` \ core_xs ->
341 returnDs (mkConsExpr ty core_x core_xs)
343 -- we create a list from the array elements and convert them into a list using
346 -- * the main disadvantage to this scheme is that `toP' traverses the list
347 -- twice: once to determine the length and a second time to put to elements
348 -- into the array; this inefficiency could be avoided by exposing some of
349 -- the innards of `PrelPArr' to the compiler (ie, have a `PrelPArrBase') so
350 -- that we can exploit the fact that we already know the length of the array
351 -- here at compile time
353 dsExpr (ExplicitPArr ty xs)
354 = dsLookupGlobalId toPName `thenDs` \toP ->
355 dsExpr (ExplicitList ty xs) `thenDs` \coreList ->
356 returnDs (mkApps (Var toP) [Type ty, coreList])
358 dsExpr (ExplicitTuple expr_list boxity)
359 = mappM dsLExpr expr_list `thenDs` \ core_exprs ->
360 returnDs (mkConApp (tupleCon boxity (length expr_list))
361 (map (Type . exprType) core_exprs ++ core_exprs))
363 dsExpr (ArithSeq expr (From from))
364 = dsExpr expr `thenDs` \ expr2 ->
365 dsLExpr from `thenDs` \ from2 ->
366 returnDs (App expr2 from2)
368 dsExpr (ArithSeq expr (FromTo from two))
369 = dsExpr expr `thenDs` \ expr2 ->
370 dsLExpr from `thenDs` \ from2 ->
371 dsLExpr two `thenDs` \ two2 ->
372 returnDs (mkApps expr2 [from2, two2])
374 dsExpr (ArithSeq expr (FromThen from thn))
375 = dsExpr expr `thenDs` \ expr2 ->
376 dsLExpr from `thenDs` \ from2 ->
377 dsLExpr thn `thenDs` \ thn2 ->
378 returnDs (mkApps expr2 [from2, thn2])
380 dsExpr (ArithSeq expr (FromThenTo from thn two))
381 = dsExpr expr `thenDs` \ expr2 ->
382 dsLExpr from `thenDs` \ from2 ->
383 dsLExpr thn `thenDs` \ thn2 ->
384 dsLExpr two `thenDs` \ two2 ->
385 returnDs (mkApps expr2 [from2, thn2, two2])
387 dsExpr (PArrSeq expr (FromTo from two))
388 = dsExpr expr `thenDs` \ expr2 ->
389 dsLExpr from `thenDs` \ from2 ->
390 dsLExpr two `thenDs` \ two2 ->
391 returnDs (mkApps expr2 [from2, two2])
393 dsExpr (PArrSeq expr (FromThenTo from thn two))
394 = dsExpr expr `thenDs` \ expr2 ->
395 dsLExpr from `thenDs` \ from2 ->
396 dsLExpr thn `thenDs` \ thn2 ->
397 dsLExpr two `thenDs` \ two2 ->
398 returnDs (mkApps expr2 [from2, thn2, two2])
400 dsExpr (PArrSeq expr _)
401 = panic "DsExpr.dsExpr: Infinite parallel array!"
402 -- the parser shouldn't have generated it and the renamer and typechecker
403 -- shouldn't have let it through
407 \underline{\bf Record construction and update}
408 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
409 For record construction we do this (assuming T has three arguments)
413 let err = /\a -> recConErr a
414 T (recConErr t1 "M.lhs/230/op1")
416 (recConErr t1 "M.lhs/230/op3")
418 @recConErr@ then converts its arugment string into a proper message
419 before printing it as
421 M.lhs, line 230: missing field op1 was evaluated
424 We also handle @C{}@ as valid construction syntax for an unlabelled
425 constructor @C@, setting all of @C@'s fields to bottom.
428 dsExpr (RecordCon (L _ data_con_id) con_expr rbinds)
429 = dsExpr con_expr `thenDs` \ con_expr' ->
431 (arg_tys, _) = tcSplitFunTys (exprType con_expr')
432 -- A newtype in the corner should be opaque;
433 -- hence TcType.tcSplitFunTys
435 mk_arg (arg_ty, lbl) -- Selector id has the field label as its name
436 = case [rhs | (L _ sel_id, rhs) <- rbinds, lbl == idName sel_id] of
437 (rhs:rhss) -> ASSERT( null rhss )
439 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
440 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
442 labels = dataConFieldLabels (idDataCon data_con_id)
443 -- The data_con_id is guaranteed to be the wrapper id of the constructor
447 then mappM unlabelled_bottom arg_tys
448 else mappM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
449 `thenDs` \ con_args ->
451 returnDs (mkApps con_expr' con_args)
454 Record update is a little harder. Suppose we have the decl:
456 data T = T1 {op1, op2, op3 :: Int}
457 | T2 {op4, op2 :: Int}
460 Then we translate as follows:
466 T1 op1 _ op3 -> T1 op1 op2 op3
467 T2 op4 _ -> T2 op4 op2
468 other -> recUpdError "M.lhs/230"
470 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
471 RHSs, and do not generate a Core constructor application directly, because the constructor
472 might do some argument-evaluation first; and may have to throw away some
476 dsExpr (RecordUpd record_expr [] record_in_ty record_out_ty)
477 = dsLExpr record_expr
479 dsExpr expr@(RecordUpd record_expr rbinds record_in_ty record_out_ty)
480 = dsLExpr record_expr `thenDs` \ record_expr' ->
482 -- Desugar the rbinds, and generate let-bindings if
483 -- necessary so that we don't lose sharing
486 in_inst_tys = tcTyConAppArgs record_in_ty -- Newtype opaque
487 out_inst_tys = tcTyConAppArgs record_out_ty -- Newtype opaque
488 in_out_ty = mkFunTy record_in_ty record_out_ty
490 mk_val_arg field old_arg_id
491 = case [rhs | (L _ sel_id, rhs) <- rbinds, field == idName sel_id] of
492 (rhs:rest) -> ASSERT(null rest) rhs
493 [] -> nlHsVar old_arg_id
496 = ASSERT( isVanillaDataCon con )
497 newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
498 -- This call to dataConInstOrigArgTys won't work for existentials
499 -- but existentials don't have record types anyway
501 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
502 (dataConFieldLabels con) arg_ids
503 rhs = foldl (\a b -> nlHsApp a b)
504 (nlHsTyApp (dataConWrapId con) out_inst_tys)
507 returnDs (mkSimpleMatch [mkPrefixConPat con (map nlVarPat arg_ids) record_in_ty] rhs)
509 -- Record stuff doesn't work for existentials
510 -- The type checker checks for this, but we need
511 -- worry only about the constructors that are to be updated
512 ASSERT2( all isVanillaDataCon cons_to_upd, ppr expr )
514 -- It's important to generate the match with matchWrapper,
515 -- and the right hand sides with applications of the wrapper Id
516 -- so that everything works when we are doing fancy unboxing on the
517 -- constructor aguments.
518 mappM mk_alt cons_to_upd `thenDs` \ alts ->
519 matchWrapper RecUpd (MatchGroup alts in_out_ty) `thenDs` \ ([discrim_var], matching_code) ->
521 returnDs (bindNonRec discrim_var record_expr' matching_code)
524 updated_fields :: [FieldLabel]
525 updated_fields = [ idName sel_id | (L _ sel_id,_) <- rbinds]
527 -- Get the type constructor from the record_in_ty
528 -- so that we are sure it'll have all its DataCons
529 -- (In GHCI, it's possible that some TyCons may not have all
530 -- their constructors, in a module-loop situation.)
531 tycon = tcTyConAppTyCon record_in_ty
532 data_cons = tyConDataCons tycon
533 cons_to_upd = filter has_all_fields data_cons
535 has_all_fields :: DataCon -> Bool
536 has_all_fields con_id
537 = all (`elem` con_fields) updated_fields
539 con_fields = dataConFieldLabels con_id
542 Here is where we desugar the Template Haskell brackets and escapes
545 -- Template Haskell stuff
547 #ifdef GHCI /* Only if bootstrapping */
548 dsExpr (HsBracketOut x ps) = dsBracket x ps
549 dsExpr (HsSpliceE s) = pprPanic "dsExpr:splice" (ppr s)
552 -- Arrow notation extension
553 dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
559 dsExpr (HsTick ix e) = do
563 -- There is a problem here. The then and else branches
564 -- have no free variables, so they are open to lifting.
565 -- We need someway of stopping this.
566 -- This will make no difference to binary coverage
567 -- (did you go here: YES or NO), but will effect accurate
570 dsExpr (HsBinTick ixT ixF e) = do
572 do { ASSERT(exprType e2 `coreEqType` boolTy)
573 mkBinaryTickBox ixT ixF e2
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)
601 go [] = dsAndThenMaybeInsertBreakpoint body
603 go (ExprStmt rhs then_expr _ : stmts)
604 = do { rhs2 <- dsAndThenMaybeInsertBreakpoint rhs
605 ; then_expr2 <- dsExpr then_expr
607 ; returnDs (mkApps then_expr2 [rhs2, rest]) }
609 go (LetStmt binds : stmts)
610 = do { rest <- bindLocalsDs (map unLoc$ collectLocalBinders binds) $
612 ; dsLocalBinds binds rest }
614 -- Notice how due to the placement of bindLocals, binders in this stmt
615 -- are available in posterior stmts but Not in this one rhs.
616 -- This is to avoid silliness in breakpoints
617 go (BindStmt pat rhs bind_op fail_op : stmts)
619 do { body <- bindLocalsDs (collectPatBinders pat) $ go stmts
620 ; var <- selectSimpleMatchVarL pat
621 ; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat
622 result_ty (cantFailMatchResult body)
623 ; match_code <- handle_failure pat match fail_op
624 ; rhs' <- dsAndThenMaybeInsertBreakpoint rhs
625 ; bind_op' <- dsExpr bind_op
626 ; returnDs (mkApps bind_op' [rhs', Lam var match_code]) }
628 -- In a do expression, pattern-match failure just calls
629 -- the monadic 'fail' rather than throwing an exception
630 handle_failure pat match fail_op
632 = do { fail_op' <- dsExpr fail_op
633 ; fail_msg <- mkStringExpr (mk_fail_msg pat)
634 ; extractMatchResult match (App fail_op' fail_msg) }
636 = extractMatchResult match (error "It can't fail")
638 mk_fail_msg pat = "Pattern match failure in do expression at " ++
639 showSDoc (ppr (getLoc pat))
642 Translation for RecStmt's:
643 -----------------------------
644 We turn (RecStmt [v1,..vn] stmts) into:
646 (v1,..,vn) <- mfix (\~(v1,..vn). do stmts
653 -> Type -- Type of the whole expression
656 dsMDo tbl stmts body result_ty
657 = go (map unLoc stmts)
659 (m_ty, b_ty) = tcSplitAppTy result_ty -- result_ty must be of the form (m b)
660 mfix_id = lookupEvidence tbl mfixName
661 return_id = lookupEvidence tbl returnMName
662 bind_id = lookupEvidence tbl bindMName
663 then_id = lookupEvidence tbl thenMName
664 fail_id = lookupEvidence tbl failMName
669 go (LetStmt binds : stmts)
670 = do { rest <- go stmts
671 ; dsLocalBinds binds rest }
673 go (ExprStmt rhs _ rhs_ty : stmts)
674 = do { rhs2 <- dsAndThenMaybeInsertBreakpoint rhs
676 ; returnDs (mkApps (Var then_id) [Type rhs_ty, Type b_ty, rhs2, rest]) }
678 go (BindStmt pat rhs _ _ : stmts)
679 = do { body <- bindLocalsDs (collectPatBinders pat) $ go stmts
680 ; var <- selectSimpleMatchVarL pat
681 ; match <- matchSinglePat (Var var) (StmtCtxt ctxt) pat
682 result_ty (cantFailMatchResult body)
683 ; fail_msg <- mkStringExpr (mk_fail_msg pat)
684 ; let fail_expr = mkApps (Var fail_id) [Type b_ty, fail_msg]
685 ; match_code <- extractMatchResult match fail_expr
687 ; rhs' <- dsAndThenMaybeInsertBreakpoint rhs
688 ; returnDs (mkApps (Var bind_id) [Type (hsLPatType pat), Type b_ty,
689 rhs', Lam var match_code]) }
691 go (RecStmt rec_stmts later_ids rec_ids rec_rets binds : stmts)
692 = ASSERT( length rec_ids > 0 )
693 ASSERT( length rec_ids == length rec_rets )
694 go (new_bind_stmt : let_stmt : stmts)
696 new_bind_stmt = mkBindStmt (mk_tup_pat later_pats) mfix_app
697 let_stmt = LetStmt (HsValBinds (ValBindsOut [(Recursive, binds)] []))
700 -- Remove the later_ids that appear (without fancy coercions)
701 -- in rec_rets, because there's no need to knot-tie them separately
702 -- See Note [RecStmt] in HsExpr
703 later_ids' = filter (`notElem` mono_rec_ids) later_ids
704 mono_rec_ids = [ id | HsVar id <- rec_rets ]
706 mfix_app = nlHsApp (nlHsTyApp mfix_id [tup_ty]) mfix_arg
707 mfix_arg = noLoc $ HsLam (MatchGroup [mkSimpleMatch [mfix_pat] body]
708 (mkFunTy tup_ty body_ty))
710 -- The rec_tup_pat must bind the rec_ids only; remember that the
711 -- trimmed_laters may share the same Names
712 -- Meanwhile, the later_pats must bind the later_vars
713 rec_tup_pats = map mk_wild_pat later_ids' ++ map nlVarPat rec_ids
714 later_pats = map nlVarPat later_ids' ++ map mk_later_pat rec_ids
715 rets = map nlHsVar later_ids' ++ map noLoc rec_rets
717 mfix_pat = noLoc $ LazyPat $ mk_tup_pat rec_tup_pats
718 body = noLoc $ HsDo ctxt rec_stmts return_app body_ty
719 body_ty = mkAppTy m_ty tup_ty
720 tup_ty = mkCoreTupTy (map idType (later_ids' ++ rec_ids))
721 -- mkCoreTupTy deals with singleton case
723 return_app = nlHsApp (nlHsTyApp return_id [tup_ty])
726 mk_wild_pat :: Id -> LPat Id
727 mk_wild_pat v = noLoc $ WildPat $ idType v
729 mk_later_pat :: Id -> LPat Id
730 mk_later_pat v | v `elem` later_ids' = mk_wild_pat v
731 | otherwise = nlVarPat v
733 mk_tup_pat :: [LPat Id] -> LPat Id
735 mk_tup_pat ps = noLoc $ mkVanillaTuplePat ps Boxed
737 mk_ret_tup :: [LHsExpr Id] -> LHsExpr Id
739 mk_ret_tup rs = noLoc $ ExplicitTuple rs Boxed