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 , WpTyApp ty <- simpWrapper w
196 = do areBreakpointsEnabled <- breakpoints_enabled
197 if areBreakpointsEnabled
199 L _ breakpointExpr <- mkBreakpointExpr loc v ty
200 dsLExpr (L loc $ HsWrap w breakpointExpr)
201 else putSrcSpanDs loc $ dsExpr expr
202 where simpWrapper (WpCompose w1 WpHole) = w1
203 simpWrapper (WpCompose WpHole w1) = w1
207 dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e
209 dsExpr :: HsExpr Id -> DsM CoreExpr
210 dsExpr (HsPar e) = dsLExpr e
211 dsExpr (ExprWithTySigOut e _) = dsLExpr e
212 dsExpr (HsVar var) = returnDs (Var var)
213 dsExpr (HsIPVar ip) = returnDs (Var (ipNameName ip))
214 dsExpr (HsLit lit) = dsLit lit
215 dsExpr (HsOverLit lit) = dsOverLit lit
216 dsExpr (HsWrap co_fn e) = dsCoercion co_fn (dsExpr e)
218 dsExpr (NegApp expr neg_expr)
219 = do { core_expr <- dsLExpr expr
220 ; core_neg <- dsExpr neg_expr
221 ; return (core_neg `App` core_expr) }
223 dsExpr expr@(HsLam a_Match)
224 = matchWrapper LambdaExpr a_Match `thenDs` \ (binders, matching_code) ->
225 returnDs (mkLams binders matching_code)
227 dsExpr expr@(HsApp fun arg)
228 = dsLExpr fun `thenDs` \ core_fun ->
229 dsLExpr arg `thenDs` \ core_arg ->
230 returnDs (core_fun `mkDsApp` core_arg)
233 Operator sections. At first it looks as if we can convert
242 But no! expr might be a redex, and we can lose laziness badly this
247 for example. So we convert instead to
249 let y = expr in \x -> op y x
251 If \tr{expr} is actually just a variable, say, then the simplifier
255 dsExpr (OpApp e1 op _ e2)
256 = dsLExpr op `thenDs` \ core_op ->
257 -- for the type of y, we need the type of op's 2nd argument
258 dsLExpr e1 `thenDs` \ x_core ->
259 dsLExpr e2 `thenDs` \ y_core ->
260 returnDs (mkDsApps core_op [x_core, y_core])
262 dsExpr (SectionL expr op) -- Desugar (e !) to ((!) e)
263 = dsLExpr op `thenDs` \ core_op ->
264 dsLExpr expr `thenDs` \ x_core ->
265 returnDs (mkDsApp core_op x_core)
267 -- dsLExpr (SectionR op expr) -- \ x -> op x expr
268 dsExpr (SectionR op expr)
269 = dsLExpr 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)
273 -- See comment with SectionL
275 dsLExpr 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 (mkDsApps core_op [Var x_id, Var y_id]))
282 dsExpr (HsSCC cc expr)
283 = dsLExpr expr `thenDs` \ core_expr ->
284 getModuleDs `thenDs` \ mod_name ->
285 returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
288 -- hdaume: core annotation
290 dsExpr (HsCoreAnn fs expr)
291 = dsLExpr expr `thenDs` \ core_expr ->
292 returnDs (Note (CoreNote $ unpackFS fs) core_expr)
294 dsExpr (HsCase discrim matches)
295 = dsLExpr discrim `thenDs` \ core_discrim ->
296 matchWrapper CaseAlt matches `thenDs` \ ([discrim_var], matching_code) ->
297 returnDs (scrungleMatch discrim_var core_discrim matching_code)
299 -- Pepe: The binds are in scope in the body but NOT in the binding group
300 -- This is to avoid silliness in breakpoints
301 dsExpr (HsLet binds body)
302 = (bindLocalsDs (map unLoc $ collectLocalBinders binds) $
303 dsAndThenMaybeInsertBreakpoint body) `thenDs` \ body' ->
304 dsLocalBinds binds body'
306 -- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
307 -- because the interpretation of `stmts' depends on what sort of thing it is.
309 dsExpr (HsDo ListComp stmts body result_ty)
310 = -- Special case for list comprehensions
311 dsListComp stmts body elt_ty
313 [elt_ty] = tcTyConAppArgs result_ty
315 dsExpr (HsDo DoExpr stmts body result_ty)
316 = dsDo stmts body result_ty
318 dsExpr (HsDo (MDoExpr tbl) stmts body result_ty)
319 = dsMDo tbl stmts body result_ty
321 dsExpr (HsDo PArrComp stmts body result_ty)
322 = -- Special case for array comprehensions
323 dsPArrComp (map unLoc stmts) body elt_ty
325 [elt_ty] = tcTyConAppArgs result_ty
327 dsExpr (HsIf guard_expr then_expr else_expr)
328 = dsLExpr guard_expr `thenDs` \ core_guard ->
329 dsLExpr then_expr `thenDs` \ core_then ->
330 dsLExpr else_expr `thenDs` \ core_else ->
331 returnDs (mkIfThenElse core_guard core_then core_else)
336 \underline{\bf Various data construction things}
337 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
339 dsExpr (ExplicitList ty xs)
342 go [] = returnDs (mkNilExpr ty)
343 go (x:xs) = dsLExpr x `thenDs` \ core_x ->
344 go xs `thenDs` \ core_xs ->
345 returnDs (mkConsExpr ty core_x core_xs)
347 -- we create a list from the array elements and convert them into a list using
350 -- * the main disadvantage to this scheme is that `toP' traverses the list
351 -- twice: once to determine the length and a second time to put to elements
352 -- into the array; this inefficiency could be avoided by exposing some of
353 -- the innards of `PrelPArr' to the compiler (ie, have a `PrelPArrBase') so
354 -- that we can exploit the fact that we already know the length of the array
355 -- here at compile time
357 dsExpr (ExplicitPArr ty xs)
358 = dsLookupGlobalId toPName `thenDs` \toP ->
359 dsExpr (ExplicitList ty xs) `thenDs` \coreList ->
360 returnDs (mkApps (Var toP) [Type ty, coreList])
362 dsExpr (ExplicitTuple expr_list boxity)
363 = mappM dsLExpr expr_list `thenDs` \ core_exprs ->
364 returnDs (mkConApp (tupleCon boxity (length expr_list))
365 (map (Type . exprType) core_exprs ++ core_exprs))
367 dsExpr (ArithSeq expr (From from))
368 = dsExpr expr `thenDs` \ expr2 ->
369 dsLExpr from `thenDs` \ from2 ->
370 returnDs (App expr2 from2)
372 dsExpr (ArithSeq expr (FromTo from two))
373 = dsExpr expr `thenDs` \ expr2 ->
374 dsLExpr from `thenDs` \ from2 ->
375 dsLExpr two `thenDs` \ two2 ->
376 returnDs (mkApps expr2 [from2, two2])
378 dsExpr (ArithSeq expr (FromThen from thn))
379 = dsExpr expr `thenDs` \ expr2 ->
380 dsLExpr from `thenDs` \ from2 ->
381 dsLExpr thn `thenDs` \ thn2 ->
382 returnDs (mkApps expr2 [from2, thn2])
384 dsExpr (ArithSeq expr (FromThenTo from thn two))
385 = dsExpr expr `thenDs` \ expr2 ->
386 dsLExpr from `thenDs` \ from2 ->
387 dsLExpr thn `thenDs` \ thn2 ->
388 dsLExpr two `thenDs` \ two2 ->
389 returnDs (mkApps expr2 [from2, thn2, two2])
391 dsExpr (PArrSeq expr (FromTo from two))
392 = dsExpr expr `thenDs` \ expr2 ->
393 dsLExpr from `thenDs` \ from2 ->
394 dsLExpr two `thenDs` \ two2 ->
395 returnDs (mkApps expr2 [from2, two2])
397 dsExpr (PArrSeq expr (FromThenTo from thn two))
398 = dsExpr expr `thenDs` \ expr2 ->
399 dsLExpr from `thenDs` \ from2 ->
400 dsLExpr thn `thenDs` \ thn2 ->
401 dsLExpr two `thenDs` \ two2 ->
402 returnDs (mkApps expr2 [from2, thn2, two2])
404 dsExpr (PArrSeq expr _)
405 = panic "DsExpr.dsExpr: Infinite parallel array!"
406 -- the parser shouldn't have generated it and the renamer and typechecker
407 -- shouldn't have let it through
411 \underline{\bf Record construction and update}
412 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
413 For record construction we do this (assuming T has three arguments)
417 let err = /\a -> recConErr a
418 T (recConErr t1 "M.lhs/230/op1")
420 (recConErr t1 "M.lhs/230/op3")
422 @recConErr@ then converts its arugment string into a proper message
423 before printing it as
425 M.lhs, line 230: missing field op1 was evaluated
428 We also handle @C{}@ as valid construction syntax for an unlabelled
429 constructor @C@, setting all of @C@'s fields to bottom.
432 dsExpr (RecordCon (L _ data_con_id) con_expr (HsRecordBinds rbinds))
433 = dsExpr con_expr `thenDs` \ con_expr' ->
435 (arg_tys, _) = tcSplitFunTys (exprType con_expr')
436 -- A newtype in the corner should be opaque;
437 -- hence TcType.tcSplitFunTys
439 mk_arg (arg_ty, lbl) -- Selector id has the field label as its name
440 = case [rhs | (L _ sel_id, rhs) <- rbinds, lbl == idName sel_id] of
441 (rhs:rhss) -> ASSERT( null rhss )
443 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
444 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
446 labels = dataConFieldLabels (idDataCon data_con_id)
447 -- The data_con_id is guaranteed to be the wrapper id of the constructor
451 then mappM unlabelled_bottom arg_tys
452 else mappM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
453 `thenDs` \ con_args ->
455 returnDs (mkApps con_expr' con_args)
458 Record update is a little harder. Suppose we have the decl:
460 data T = T1 {op1, op2, op3 :: Int}
461 | T2 {op4, op2 :: Int}
464 Then we translate as follows:
470 T1 op1 _ op3 -> T1 op1 op2 op3
471 T2 op4 _ -> T2 op4 op2
472 other -> recUpdError "M.lhs/230"
474 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
475 RHSs, and do not generate a Core constructor application directly, because the constructor
476 might do some argument-evaluation first; and may have to throw away some
480 dsExpr (RecordUpd record_expr (HsRecordBinds []) record_in_ty record_out_ty)
481 = dsLExpr record_expr
483 dsExpr expr@(RecordUpd record_expr (HsRecordBinds rbinds) record_in_ty record_out_ty)
484 = dsLExpr record_expr `thenDs` \ record_expr' ->
486 -- Desugar the rbinds, and generate let-bindings if
487 -- necessary so that we don't lose sharing
490 in_inst_tys = tcTyConAppArgs record_in_ty -- Newtype opaque
491 out_inst_tys = tcTyConAppArgs record_out_ty -- Newtype opaque
492 in_out_ty = mkFunTy record_in_ty record_out_ty
494 mk_val_arg field old_arg_id
495 = case [rhs | (L _ sel_id, rhs) <- rbinds, field == idName sel_id] of
496 (rhs:rest) -> ASSERT(null rest) rhs
497 [] -> nlHsVar old_arg_id
500 = ASSERT( isVanillaDataCon con )
501 newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
502 -- This call to dataConInstOrigArgTys won't work for existentials
503 -- but existentials don't have record types anyway
505 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
506 (dataConFieldLabels con) arg_ids
507 rhs = foldl (\a b -> nlHsApp a b)
508 (nlHsTyApp (dataConWrapId con) out_inst_tys)
511 returnDs (mkSimpleMatch [mkPrefixConPat con (map nlVarPat arg_ids) record_in_ty] rhs)
513 -- Record stuff doesn't work for existentials
514 -- The type checker checks for this, but we need
515 -- worry only about the constructors that are to be updated
516 ASSERT2( all isVanillaDataCon cons_to_upd, ppr expr )
518 -- It's important to generate the match with matchWrapper,
519 -- and the right hand sides with applications of the wrapper Id
520 -- so that everything works when we are doing fancy unboxing on the
521 -- constructor aguments.
522 mappM mk_alt cons_to_upd `thenDs` \ alts ->
523 matchWrapper RecUpd (MatchGroup alts in_out_ty) `thenDs` \ ([discrim_var], matching_code) ->
525 returnDs (bindNonRec discrim_var record_expr' matching_code)
528 updated_fields :: [FieldLabel]
529 updated_fields = [ idName sel_id | (L _ sel_id,_) <- rbinds]
531 -- Get the type constructor from the record_in_ty
532 -- so that we are sure it'll have all its DataCons
533 -- (In GHCI, it's possible that some TyCons may not have all
534 -- their constructors, in a module-loop situation.)
535 tycon = tcTyConAppTyCon record_in_ty
536 data_cons = tyConDataCons tycon
537 cons_to_upd = filter has_all_fields data_cons
539 has_all_fields :: DataCon -> Bool
540 has_all_fields con_id
541 = all (`elem` con_fields) updated_fields
543 con_fields = dataConFieldLabels con_id
546 Here is where we desugar the Template Haskell brackets and escapes
549 -- Template Haskell stuff
551 #ifdef GHCI /* Only if bootstrapping */
552 dsExpr (HsBracketOut x ps) = dsBracket x ps
553 dsExpr (HsSpliceE s) = pprPanic "dsExpr:splice" (ppr s)
556 -- Arrow notation extension
557 dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
563 dsExpr (HsTick ix e) = do
567 -- There is a problem here. The then and else branches
568 -- have no free variables, so they are open to lifting.
569 -- We need someway of stopping this.
570 -- This will make no difference to binary coverage
571 -- (did you go here: YES or NO), but will effect accurate
574 dsExpr (HsBinTick ixT ixF e) = do
576 do { ASSERT(exprType e2 `coreEqType` boolTy)
577 mkBinaryTickBox ixT ixF e2
584 -- HsSyn constructs that just shouldn't be here:
585 dsExpr (ExprWithTySig _ _) = panic "dsExpr:ExprWithTySig"
590 %--------------------------------------------------------------------
592 Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
593 handled in DsListComp). Basically does the translation given in the
599 -> Type -- Type of the whole expression
602 dsDo stmts body result_ty
603 = go (map unLoc stmts)
605 go [] = dsAndThenMaybeInsertBreakpoint body
607 go (ExprStmt rhs then_expr _ : stmts)
608 = do { rhs2 <- dsAndThenMaybeInsertBreakpoint rhs
609 ; then_expr2 <- dsExpr then_expr
611 ; returnDs (mkApps then_expr2 [rhs2, rest]) }
613 go (LetStmt binds : stmts)
614 = do { rest <- bindLocalsDs (map unLoc$ collectLocalBinders binds) $
616 ; dsLocalBinds binds rest }
618 -- Notice how due to the placement of bindLocals, binders in this stmt
619 -- are available in posterior stmts but Not in this one rhs.
620 -- This is to avoid silliness in breakpoints
621 go (BindStmt pat rhs bind_op fail_op : stmts)
623 do { body <- bindLocalsDs (collectPatBinders pat) $ go stmts
624 ; var <- selectSimpleMatchVarL pat
625 ; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat
626 result_ty (cantFailMatchResult body)
627 ; match_code <- handle_failure pat match fail_op
628 ; rhs' <- dsAndThenMaybeInsertBreakpoint rhs
629 ; bind_op' <- dsExpr bind_op
630 ; returnDs (mkApps bind_op' [rhs', Lam var match_code]) }
632 -- In a do expression, pattern-match failure just calls
633 -- the monadic 'fail' rather than throwing an exception
634 handle_failure pat match fail_op
636 = do { fail_op' <- dsExpr fail_op
637 ; fail_msg <- mkStringExpr (mk_fail_msg pat)
638 ; extractMatchResult match (App fail_op' fail_msg) }
640 = extractMatchResult match (error "It can't fail")
642 mk_fail_msg pat = "Pattern match failure in do expression at " ++
643 showSDoc (ppr (getLoc pat))
646 Translation for RecStmt's:
647 -----------------------------
648 We turn (RecStmt [v1,..vn] stmts) into:
650 (v1,..,vn) <- mfix (\~(v1,..vn). do stmts
657 -> Type -- Type of the whole expression
660 dsMDo tbl stmts body result_ty
661 = go (map unLoc stmts)
663 (m_ty, b_ty) = tcSplitAppTy result_ty -- result_ty must be of the form (m b)
664 mfix_id = lookupEvidence tbl mfixName
665 return_id = lookupEvidence tbl returnMName
666 bind_id = lookupEvidence tbl bindMName
667 then_id = lookupEvidence tbl thenMName
668 fail_id = lookupEvidence tbl failMName
673 go (LetStmt binds : stmts)
674 = do { rest <- go stmts
675 ; dsLocalBinds binds rest }
677 go (ExprStmt rhs _ rhs_ty : stmts)
678 = do { rhs2 <- dsAndThenMaybeInsertBreakpoint rhs
680 ; returnDs (mkApps (Var then_id) [Type rhs_ty, Type b_ty, rhs2, rest]) }
682 go (BindStmt pat rhs _ _ : stmts)
683 = do { body <- bindLocalsDs (collectPatBinders pat) $ go stmts
684 ; var <- selectSimpleMatchVarL pat
685 ; match <- matchSinglePat (Var var) (StmtCtxt ctxt) pat
686 result_ty (cantFailMatchResult body)
687 ; fail_msg <- mkStringExpr (mk_fail_msg pat)
688 ; let fail_expr = mkApps (Var fail_id) [Type b_ty, fail_msg]
689 ; match_code <- extractMatchResult match fail_expr
691 ; rhs' <- dsAndThenMaybeInsertBreakpoint rhs
692 ; returnDs (mkApps (Var bind_id) [Type (hsLPatType pat), Type b_ty,
693 rhs', Lam var match_code]) }
695 go (RecStmt rec_stmts later_ids rec_ids rec_rets binds : stmts)
696 = ASSERT( length rec_ids > 0 )
697 ASSERT( length rec_ids == length rec_rets )
698 go (new_bind_stmt : let_stmt : stmts)
700 new_bind_stmt = mkBindStmt (mk_tup_pat later_pats) mfix_app
701 let_stmt = LetStmt (HsValBinds (ValBindsOut [(Recursive, binds)] []))
704 -- Remove the later_ids that appear (without fancy coercions)
705 -- in rec_rets, because there's no need to knot-tie them separately
706 -- See Note [RecStmt] in HsExpr
707 later_ids' = filter (`notElem` mono_rec_ids) later_ids
708 mono_rec_ids = [ id | HsVar id <- rec_rets ]
710 mfix_app = nlHsApp (nlHsTyApp mfix_id [tup_ty]) mfix_arg
711 mfix_arg = noLoc $ HsLam (MatchGroup [mkSimpleMatch [mfix_pat] body]
712 (mkFunTy tup_ty body_ty))
714 -- The rec_tup_pat must bind the rec_ids only; remember that the
715 -- trimmed_laters may share the same Names
716 -- Meanwhile, the later_pats must bind the later_vars
717 rec_tup_pats = map mk_wild_pat later_ids' ++ map nlVarPat rec_ids
718 later_pats = map nlVarPat later_ids' ++ map mk_later_pat rec_ids
719 rets = map nlHsVar later_ids' ++ map noLoc rec_rets
721 mfix_pat = noLoc $ LazyPat $ mk_tup_pat rec_tup_pats
722 body = noLoc $ HsDo ctxt rec_stmts return_app body_ty
723 body_ty = mkAppTy m_ty tup_ty
724 tup_ty = mkCoreTupTy (map idType (later_ids' ++ rec_ids))
725 -- mkCoreTupTy deals with singleton case
727 return_app = nlHsApp (nlHsTyApp return_id [tup_ty])
730 mk_wild_pat :: Id -> LPat Id
731 mk_wild_pat v = noLoc $ WildPat $ idType v
733 mk_later_pat :: Id -> LPat Id
734 mk_later_pat v | v `elem` later_ids' = mk_wild_pat v
735 | otherwise = nlVarPat v
737 mk_tup_pat :: [LPat Id] -> LPat Id
739 mk_tup_pat ps = noLoc $ mkVanillaTuplePat ps Boxed
741 mk_ret_tup :: [LHsExpr Id] -> LHsExpr Id
743 mk_ret_tup rs = noLoc $ ExplicitTuple rs Boxed