Fix warning (FIX validate)
[ghc-hetmet.git] / compiler / deSugar / DsExpr.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Desugaring exporessions.
7
8 \begin{code}
9 {-# OPTIONS -fno-warn-incomplete-patterns #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 -- for details
15
16 module DsExpr ( dsExpr, dsLExpr, dsLocalBinds, dsValBinds, dsLit ) where
17
18 #include "HsVersions.h"
19
20
21 import Match
22 import MatchLit
23 import DsBinds
24 import DsGRHSs
25 import DsListComp
26 import DsUtils
27 import DsArrows
28 import DsMonad
29 import Name
30
31 #ifdef GHCI
32 import PrelNames
33         -- Template Haskell stuff iff bootstrapped
34 import DsMeta
35 #endif
36
37 import HsSyn
38 import TcHsSyn
39
40 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
41 --     needs to see source types
42 import TcType
43 import Type
44 import CoreSyn
45 import CoreUtils
46
47 import CostCentre
48 import Id
49 import PrelInfo
50 import DataCon
51 import TysWiredIn
52 import BasicTypes
53 import PrelNames
54 import SrcLoc
55 import Util
56 import Bag
57 import Outputable
58 import FastString
59 \end{code}
60
61
62 %************************************************************************
63 %*                                                                      *
64                 dsLocalBinds, dsValBinds
65 %*                                                                      *
66 %************************************************************************
67
68 \begin{code}
69 dsLocalBinds :: HsLocalBinds Id -> CoreExpr -> DsM CoreExpr
70 dsLocalBinds EmptyLocalBinds    body = return body
71 dsLocalBinds (HsValBinds binds) body = dsValBinds binds body
72 dsLocalBinds (HsIPBinds binds)  body = dsIPBinds  binds body
73
74 -------------------------
75 dsValBinds :: HsValBinds Id -> CoreExpr -> DsM CoreExpr
76 dsValBinds (ValBindsOut binds _) body = foldrM ds_val_bind body binds
77
78 -------------------------
79 dsIPBinds :: HsIPBinds Id -> CoreExpr -> DsM CoreExpr
80 dsIPBinds (IPBinds ip_binds dict_binds) body
81   = do  { prs <- dsLHsBinds dict_binds
82         ; let inner = Let (Rec prs) body
83                 -- The dict bindings may not be in 
84                 -- dependency order; hence Rec
85         ; foldrM ds_ip_bind inner ip_binds }
86   where
87     ds_ip_bind (L _ (IPBind n e)) body
88       = do e' <- dsLExpr e
89            return (Let (NonRec (ipNameName n) e') body)
90
91 -------------------------
92 ds_val_bind :: (RecFlag, LHsBinds Id) -> CoreExpr -> DsM CoreExpr
93 -- Special case for bindings which bind unlifted variables
94 -- We need to do a case right away, rather than building
95 -- a tuple and doing selections.
96 -- Silently ignore INLINE and SPECIALISE pragmas...
97 ds_val_bind (NonRecursive, hsbinds) body
98   | [L _ (AbsBinds [] [] exports binds)] <- bagToList hsbinds,
99     (L loc bind : null_binds) <- bagToList binds,
100     isBangHsBind bind
101     || isUnboxedTupleBind bind
102     || or [isUnLiftedType (idType g) | (_, g, _, _) <- exports]
103   = let
104       body_w_exports                  = foldr bind_export body exports
105       bind_export (tvs, g, l, _) body = ASSERT( null tvs )
106                                         bindNonRec g (Var l) body
107     in
108     ASSERT (null null_binds)
109         -- Non-recursive, non-overloaded bindings only come in ones
110         -- ToDo: in some bizarre case it's conceivable that there
111         --       could be dict binds in the 'binds'.  (See the notes
112         --       below.  Then pattern-match would fail.  Urk.)
113     putSrcSpanDs loc    $
114     case bind of
115       FunBind { fun_id = L _ fun, fun_matches = matches, fun_co_fn = co_fn, 
116                 fun_tick = tick, fun_infix = inf }
117         -> do (args, rhs) <- matchWrapper (FunRhs (idName fun ) inf) matches
118               MASSERT( null args ) -- Functions aren't lifted
119               MASSERT( isIdHsWrapper co_fn )
120               rhs' <- mkOptTickBox tick rhs
121               return (bindNonRec fun rhs' body_w_exports)
122
123       PatBind {pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty }
124         ->      -- let C x# y# = rhs in body
125                 -- ==> case rhs of C x# y# -> body
126            putSrcSpanDs loc                     $
127            do { rhs <- dsGuarded grhss ty
128               ; let upat = unLoc pat
129                     eqn = EqnInfo { eqn_pats = [upat], 
130                                     eqn_rhs = cantFailMatchResult body_w_exports }
131               ; var    <- selectMatchVar upat
132               ; result <- matchEquations PatBindRhs [var] [eqn] (exprType body)
133               ; return (scrungleMatch var rhs result) }
134
135       _ -> pprPanic "dsLet: unlifted" (pprLHsBinds hsbinds $$ ppr body)
136
137
138 -- Ordinary case for bindings; none should be unlifted
139 ds_val_bind (_is_rec, binds) body
140   = do  { prs <- dsLHsBinds binds
141         ; ASSERT( not (any (isUnLiftedType . idType . fst) prs) )
142           case prs of
143             [] -> return body
144             _  -> return (Let (Rec prs) body) }
145         -- Use a Rec regardless of is_rec. 
146         -- Why? Because it allows the binds to be all
147         -- mixed up, which is what happens in one rare case
148         -- Namely, for an AbsBind with no tyvars and no dicts,
149         --         but which does have dictionary bindings.
150         -- See notes with TcSimplify.inferLoop [NO TYVARS]
151         -- It turned out that wrapping a Rec here was the easiest solution
152         --
153         -- NB The previous case dealt with unlifted bindings, so we
154         --    only have to deal with lifted ones now; so Rec is ok
155
156 isUnboxedTupleBind :: HsBind Id -> Bool
157 isUnboxedTupleBind (PatBind { pat_rhs_ty = ty }) = isUnboxedTupleType ty
158 isUnboxedTupleBind _                             = False
159
160 scrungleMatch :: Id -> CoreExpr -> CoreExpr -> CoreExpr
161 -- Returns something like (let var = scrut in body)
162 -- but if var is an unboxed-tuple type, it inlines it in a fragile way
163 -- Special case to handle unboxed tuple patterns; they can't appear nested
164 -- The idea is that 
165 --      case e of (# p1, p2 #) -> rhs
166 -- should desugar to
167 --      case e of (# x1, x2 #) -> ... match p1, p2 ...
168 -- NOT
169 --      let x = e in case x of ....
170 --
171 -- But there may be a big 
172 --      let fail = ... in case e of ...
173 -- wrapping the whole case, which complicates matters slightly
174 -- It all seems a bit fragile.  Test is dsrun013.
175
176 scrungleMatch var scrut body
177   | isUnboxedTupleType (idType var) = scrungle body
178   | otherwise                       = bindNonRec var scrut body
179   where
180     scrungle (Case (Var x) bndr ty alts)
181                     | x == var = Case scrut bndr ty alts
182     scrungle (Let binds body)  = Let binds (scrungle body)
183     scrungle other = panic ("scrungleMatch: tuple pattern:\n" ++ showSDoc (ppr other))
184
185 \end{code}
186
187 %************************************************************************
188 %*                                                                      *
189 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
190 %*                                                                      *
191 %************************************************************************
192
193 \begin{code}
194 dsLExpr :: LHsExpr Id -> DsM CoreExpr
195
196 dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e
197
198 dsExpr :: HsExpr Id -> DsM CoreExpr
199 dsExpr (HsPar e)              = dsLExpr e
200 dsExpr (ExprWithTySigOut e _) = dsLExpr e
201 dsExpr (HsVar var)            = return (Var var)
202 dsExpr (HsIPVar ip)           = return (Var (ipNameName ip))
203 dsExpr (HsLit lit)            = dsLit lit
204 dsExpr (HsOverLit lit)        = dsOverLit lit
205 dsExpr (HsWrap co_fn e)       = dsCoercion co_fn (dsExpr e)
206
207 dsExpr (NegApp expr neg_expr) 
208   = App <$> dsExpr neg_expr <*> dsLExpr expr
209
210 dsExpr (HsLam a_Match)
211   = uncurry mkLams <$> matchWrapper LambdaExpr a_Match
212
213 dsExpr (HsApp fun arg)
214   = mkDsApp <$> dsLExpr fun <*>  dsLExpr arg
215 \end{code}
216
217 Operator sections.  At first it looks as if we can convert
218 \begin{verbatim}
219         (expr op)
220 \end{verbatim}
221 to
222 \begin{verbatim}
223         \x -> op expr x
224 \end{verbatim}
225
226 But no!  expr might be a redex, and we can lose laziness badly this
227 way.  Consider
228 \begin{verbatim}
229         map (expr op) xs
230 \end{verbatim}
231 for example.  So we convert instead to
232 \begin{verbatim}
233         let y = expr in \x -> op y x
234 \end{verbatim}
235 If \tr{expr} is actually just a variable, say, then the simplifier
236 will sort it out.
237
238 \begin{code}
239 dsExpr (OpApp e1 op _ e2)
240   = -- for the type of y, we need the type of op's 2nd argument
241     mkDsApps <$> dsLExpr op <*> mapM dsLExpr [e1, e2]
242     
243 dsExpr (SectionL expr op)       -- Desugar (e !) to ((!) e)
244   = mkDsApp <$> dsLExpr op <*> dsLExpr expr
245
246 -- dsLExpr (SectionR op expr)   -- \ x -> op x expr
247 dsExpr (SectionR op expr) = do
248     core_op <- dsLExpr op
249     -- for the type of x, we need the type of op's 2nd argument
250     let (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
251         -- See comment with SectionL
252     y_core <- dsLExpr expr
253     x_id <- newSysLocalDs x_ty
254     y_id <- newSysLocalDs y_ty
255     return (bindNonRec y_id y_core $
256             Lam x_id (mkDsApps core_op [Var x_id, Var y_id]))
257
258 dsExpr (HsSCC cc expr) = do
259     mod_name <- getModuleDs
260     Note (SCC (mkUserCC cc mod_name)) <$> dsLExpr expr
261
262
263 -- hdaume: core annotation
264
265 dsExpr (HsCoreAnn fs expr)
266   = Note (CoreNote $ unpackFS fs) <$> dsLExpr expr
267
268 dsExpr (HsCase discrim matches) = do
269     core_discrim <- dsLExpr discrim
270     ([discrim_var], matching_code) <- matchWrapper CaseAlt matches
271     return (scrungleMatch discrim_var core_discrim matching_code)
272
273 -- Pepe: The binds are in scope in the body but NOT in the binding group
274 --       This is to avoid silliness in breakpoints
275 dsExpr (HsLet binds body) = do
276     body' <- dsLExpr body
277     dsLocalBinds binds body'
278
279 -- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
280 -- because the interpretation of `stmts' depends on what sort of thing it is.
281 --
282 dsExpr (HsDo ListComp stmts body result_ty)
283   =     -- Special case for list comprehensions
284     dsListComp stmts body elt_ty
285   where
286     [elt_ty] = tcTyConAppArgs result_ty
287
288 dsExpr (HsDo DoExpr stmts body result_ty)
289   = dsDo stmts body result_ty
290
291 dsExpr (HsDo (MDoExpr tbl) stmts body result_ty)
292   = dsMDo tbl stmts body result_ty
293
294 dsExpr (HsDo PArrComp stmts body result_ty)
295   =     -- Special case for array comprehensions
296     dsPArrComp (map unLoc stmts) body elt_ty
297   where
298     [elt_ty] = tcTyConAppArgs result_ty
299
300 dsExpr (HsIf guard_expr then_expr else_expr)
301   = mkIfThenElse <$> dsLExpr guard_expr <*> dsLExpr then_expr <*> dsLExpr else_expr
302 \end{code}
303
304
305 \noindent
306 \underline{\bf Various data construction things}
307 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
308 \begin{code}
309 dsExpr (ExplicitList ty xs)
310   = go xs
311   where
312     go []     = return (mkNilExpr ty)
313     go (x:xs) = mkConsExpr ty <$> dsLExpr x <*> go xs
314
315 -- we create a list from the array elements and convert them into a list using
316 -- `PrelPArr.toP'
317 --
318 --  * the main disadvantage to this scheme is that `toP' traverses the list
319 --   twice: once to determine the length and a second time to put to elements
320 --   into the array; this inefficiency could be avoided by exposing some of
321 --   the innards of `PrelPArr' to the compiler (ie, have a `PrelPArrBase') so
322 --   that we can exploit the fact that we already know the length of the array
323 --   here at compile time
324 --
325 dsExpr (ExplicitPArr ty xs) = do
326     toP <- dsLookupGlobalId toPName
327     coreList <- dsExpr (ExplicitList ty xs)
328     return (mkApps (Var toP) [Type ty, coreList])
329
330 dsExpr (ExplicitTuple expr_list boxity) = do
331     core_exprs <- mapM dsLExpr expr_list
332     return (mkConApp (tupleCon boxity (length expr_list))
333                   (map (Type .  exprType) core_exprs ++ core_exprs))
334
335 dsExpr (ArithSeq expr (From from))
336   = App <$> dsExpr expr <*> dsLExpr from
337
338 dsExpr (ArithSeq expr (FromTo from to))
339   = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, to]
340
341 dsExpr (ArithSeq expr (FromThen from thn))
342   = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, thn]
343
344 dsExpr (ArithSeq expr (FromThenTo from thn to))
345   = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, thn, to]
346
347 dsExpr (PArrSeq expr (FromTo from to))
348   = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, to]
349
350 dsExpr (PArrSeq expr (FromThenTo from thn to))
351   = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, thn, to]
352
353 dsExpr (PArrSeq _ _)
354   = panic "DsExpr.dsExpr: Infinite parallel array!"
355     -- the parser shouldn't have generated it and the renamer and typechecker
356     -- shouldn't have let it through
357 \end{code}
358
359 \noindent
360 \underline{\bf Record construction and update}
361 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
362 For record construction we do this (assuming T has three arguments)
363 \begin{verbatim}
364         T { op2 = e }
365 ==>
366         let err = /\a -> recConErr a 
367         T (recConErr t1 "M.lhs/230/op1") 
368           e 
369           (recConErr t1 "M.lhs/230/op3")
370 \end{verbatim}
371 @recConErr@ then converts its arugment string into a proper message
372 before printing it as
373 \begin{verbatim}
374         M.lhs, line 230: missing field op1 was evaluated
375 \end{verbatim}
376
377 We also handle @C{}@ as valid construction syntax for an unlabelled
378 constructor @C@, setting all of @C@'s fields to bottom.
379
380 \begin{code}
381 dsExpr (RecordCon (L _ data_con_id) con_expr rbinds) = do
382     con_expr' <- dsExpr con_expr
383     let
384         (arg_tys, _) = tcSplitFunTys (exprType con_expr')
385         -- A newtype in the corner should be opaque; 
386         -- hence TcType.tcSplitFunTys
387
388         mk_arg (arg_ty, lbl)    -- Selector id has the field label as its name
389           = case findField (rec_flds rbinds) lbl of
390               (rhs:rhss) -> ASSERT( null rhss )
391                             dsLExpr rhs
392               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
393         unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
394
395         labels = dataConFieldLabels (idDataCon data_con_id)
396         -- The data_con_id is guaranteed to be the wrapper id of the constructor
397     
398     con_args <- if null labels
399                 then mapM unlabelled_bottom arg_tys
400                 else mapM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels)
401     
402     return (mkApps con_expr' con_args)
403 \end{code}
404
405 Record update is a little harder. Suppose we have the decl:
406 \begin{verbatim}
407         data T = T1 {op1, op2, op3 :: Int}
408                | T2 {op4, op2 :: Int}
409                | T3
410 \end{verbatim}
411 Then we translate as follows:
412 \begin{verbatim}
413         r { op2 = e }
414 ===>
415         let op2 = e in
416         case r of
417           T1 op1 _ op3 -> T1 op1 op2 op3
418           T2 op4 _     -> T2 op4 op2
419           other        -> recUpdError "M.lhs/230"
420 \end{verbatim}
421 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
422 RHSs, and do not generate a Core constructor application directly, because the constructor
423 might do some argument-evaluation first; and may have to throw away some
424 dictionaries.
425
426 \begin{code}
427 dsExpr expr@(RecordUpd record_expr (HsRecFields { rec_flds = fields })
428                        cons_to_upd in_inst_tys out_inst_tys)
429   | null fields
430   = dsLExpr record_expr
431   | otherwise
432   =     -- Record stuff doesn't work for existentials
433         -- The type checker checks for this, but we need 
434         -- worry only about the constructors that are to be updated
435     ASSERT2( notNull cons_to_upd && all isVanillaDataCon cons_to_upd, ppr expr )
436
437     do  { record_expr' <- dsLExpr record_expr
438         ; let   -- Awkwardly, for families, the match goes 
439                 -- from instance type to family type
440                 tycon     = dataConTyCon (head cons_to_upd)
441                 in_ty     = mkTyConApp tycon in_inst_tys
442                 in_out_ty = mkFunTy in_ty
443                                     (mkFamilyTyConApp tycon out_inst_tys)
444
445                 mk_val_arg field old_arg_id 
446                   = case findField fields field  of
447                       (rhs:rest) -> ASSERT(null rest) rhs
448                       []         -> nlHsVar old_arg_id
449
450                 mk_alt con
451                   = ASSERT( isVanillaDataCon con )
452                     do  { arg_ids <- newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys)
453                         -- This call to dataConInstOrigArgTys won't work for existentials
454                         -- but existentials don't have record types anyway
455                         ; let val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
456                                                 (dataConFieldLabels con) arg_ids
457                               rhs = foldl (\a b -> nlHsApp a b)
458                                           (nlHsTyApp (dataConWrapId con) out_inst_tys)
459                                           val_args
460                               pat = mkPrefixConPat con (map nlVarPat arg_ids) in_ty
461
462                         ; return (mkSimpleMatch [pat] rhs) }
463
464         -- It's important to generate the match with matchWrapper,
465         -- and the right hand sides with applications of the wrapper Id
466         -- so that everything works when we are doing fancy unboxing on the
467         -- constructor aguments.
468         ; alts <- mapM mk_alt cons_to_upd
469         ; ([discrim_var], matching_code) <- matchWrapper RecUpd (MatchGroup alts in_out_ty)
470
471         ; return (bindNonRec discrim_var record_expr' matching_code) }
472 \end{code}
473
474 Here is where we desugar the Template Haskell brackets and escapes
475
476 \begin{code}
477 -- Template Haskell stuff
478
479 #ifdef GHCI     /* Only if bootstrapping */
480 dsExpr (HsBracketOut x ps) = dsBracket x ps
481 dsExpr (HsSpliceE s)       = pprPanic "dsExpr:splice" (ppr s)
482 #endif
483
484 -- Arrow notation extension
485 dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
486 \end{code}
487
488 Hpc Support 
489
490 \begin{code}
491 dsExpr (HsTick ix vars e) = do
492   e' <- dsLExpr e
493   mkTickBox ix vars e'
494
495 -- There is a problem here. The then and else branches
496 -- have no free variables, so they are open to lifting.
497 -- We need someway of stopping this.
498 -- This will make no difference to binary coverage
499 -- (did you go here: YES or NO), but will effect accurate
500 -- tick counting.
501
502 dsExpr (HsBinTick ixT ixF e) = do
503   e2 <- dsLExpr e
504   do { ASSERT(exprType e2 `coreEqType` boolTy)
505        mkBinaryTickBox ixT ixF e2
506      }
507 \end{code}
508
509 \begin{code}
510
511 #ifdef DEBUG
512 -- HsSyn constructs that just shouldn't be here:
513 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
514 #endif
515
516
517 findField :: [HsRecField Id arg] -> Name -> [arg]
518 findField rbinds lbl 
519   = [rhs | HsRecField { hsRecFieldId = id, hsRecFieldArg = rhs } <- rbinds 
520          , lbl == idName (unLoc id) ]
521 \end{code}
522
523 %--------------------------------------------------------------------
524
525 Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
526 handled in DsListComp).  Basically does the translation given in the
527 Haskell 98 report:
528
529 \begin{code}
530 dsDo    :: [LStmt Id]
531         -> LHsExpr Id
532         -> Type                 -- Type of the whole expression
533         -> DsM CoreExpr
534
535 dsDo stmts body _result_ty
536   = go (map unLoc stmts)
537   where
538     go [] = dsLExpr body
539     
540     go (ExprStmt rhs then_expr _ : stmts)
541       = do { rhs2 <- dsLExpr rhs
542            ; then_expr2 <- dsExpr then_expr
543            ; rest <- go stmts
544            ; return (mkApps then_expr2 [rhs2, rest]) }
545     
546     go (LetStmt binds : stmts)
547       = do { rest <- go stmts
548            ; dsLocalBinds binds rest }
549
550     go (BindStmt pat rhs bind_op fail_op : stmts)
551       = 
552        do  { body     <- go stmts
553            ; rhs'     <- dsLExpr rhs
554            ; bind_op' <- dsExpr bind_op
555            ; var   <- selectSimpleMatchVarL pat
556            ; let bind_ty = exprType bind_op'    -- rhs -> (pat -> res1) -> res2
557                  res1_ty = funResultTy (funArgTy (funResultTy bind_ty))
558            ; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat
559                                      res1_ty (cantFailMatchResult body)
560            ; match_code <- handle_failure pat match fail_op
561            ; return (mkApps bind_op' [rhs', Lam var match_code]) }
562     
563     -- In a do expression, pattern-match failure just calls
564     -- the monadic 'fail' rather than throwing an exception
565     handle_failure pat match fail_op
566       | matchCanFail match
567       = do { fail_op' <- dsExpr fail_op
568            ; fail_msg <- mkStringExpr (mk_fail_msg pat)
569            ; extractMatchResult match (App fail_op' fail_msg) }
570       | otherwise
571       = extractMatchResult match (error "It can't fail") 
572
573 mk_fail_msg :: Located e -> String
574 mk_fail_msg pat = "Pattern match failure in do expression at " ++ 
575                   showSDoc (ppr (getLoc pat))
576 \end{code}
577
578 Translation for RecStmt's: 
579 -----------------------------
580 We turn (RecStmt [v1,..vn] stmts) into:
581   
582   (v1,..,vn) <- mfix (\~(v1,..vn). do stmts
583                                       return (v1,..vn))
584
585 \begin{code}
586 dsMDo   :: PostTcTable
587         -> [LStmt Id]
588         -> LHsExpr Id
589         -> Type                 -- Type of the whole expression
590         -> DsM CoreExpr
591
592 dsMDo tbl stmts body result_ty
593   = go (map unLoc stmts)
594   where
595     (m_ty, b_ty) = tcSplitAppTy result_ty       -- result_ty must be of the form (m b)
596     mfix_id   = lookupEvidence tbl mfixName
597     return_id = lookupEvidence tbl returnMName
598     bind_id   = lookupEvidence tbl bindMName
599     then_id   = lookupEvidence tbl thenMName
600     fail_id   = lookupEvidence tbl failMName
601     ctxt      = MDoExpr tbl
602
603     go [] = dsLExpr body
604     
605     go (LetStmt binds : stmts)
606       = do { rest <- go stmts
607            ; dsLocalBinds binds rest }
608
609     go (ExprStmt rhs _ rhs_ty : stmts)
610       = do { rhs2 <- dsLExpr rhs
611            ; rest <- go stmts
612            ; return (mkApps (Var then_id) [Type rhs_ty, Type b_ty, rhs2, rest]) }
613     
614     go (BindStmt pat rhs _ _ : stmts)
615       = do { body  <- go stmts
616            ; var   <- selectSimpleMatchVarL pat
617            ; match <- matchSinglePat (Var var) (StmtCtxt ctxt) pat
618                                   result_ty (cantFailMatchResult body)
619            ; fail_msg   <- mkStringExpr (mk_fail_msg pat)
620            ; let fail_expr = mkApps (Var fail_id) [Type b_ty, fail_msg]
621            ; match_code <- extractMatchResult match fail_expr
622
623            ; rhs'       <- dsLExpr rhs
624            ; return (mkApps (Var bind_id) [Type (hsLPatType pat), Type b_ty, 
625                                              rhs', Lam var match_code]) }
626     
627     go (RecStmt rec_stmts later_ids rec_ids rec_rets binds : stmts)
628       = ASSERT( length rec_ids > 0 )
629         ASSERT( length rec_ids == length rec_rets )
630         go (new_bind_stmt : let_stmt : stmts)
631       where
632         new_bind_stmt = mkBindStmt (mk_tup_pat later_pats) mfix_app
633         let_stmt = LetStmt (HsValBinds (ValBindsOut [(Recursive, binds)] []))
634
635         
636                 -- Remove the later_ids that appear (without fancy coercions) 
637                 -- in rec_rets, because there's no need to knot-tie them separately
638                 -- See Note [RecStmt] in HsExpr
639         later_ids'   = filter (`notElem` mono_rec_ids) later_ids
640         mono_rec_ids = [ id | HsVar id <- rec_rets ]
641     
642         mfix_app = nlHsApp (nlHsTyApp mfix_id [tup_ty]) mfix_arg
643         mfix_arg = noLoc $ HsLam (MatchGroup [mkSimpleMatch [mfix_pat] body]
644                                              (mkFunTy tup_ty body_ty))
645
646         -- The rec_tup_pat must bind the rec_ids only; remember that the 
647         --      trimmed_laters may share the same Names
648         -- Meanwhile, the later_pats must bind the later_vars
649         rec_tup_pats = map mk_wild_pat later_ids' ++ map nlVarPat rec_ids
650         later_pats   = map nlVarPat    later_ids' ++ map mk_later_pat rec_ids
651         rets         = map nlHsVar     later_ids' ++ map noLoc rec_rets
652
653         mfix_pat = noLoc $ LazyPat $ mk_tup_pat rec_tup_pats
654         body     = noLoc $ HsDo ctxt rec_stmts return_app body_ty
655         body_ty = mkAppTy m_ty tup_ty
656         tup_ty  = mkCoreTupTy (map idType (later_ids' ++ rec_ids))
657                   -- mkCoreTupTy deals with singleton case
658
659         return_app  = nlHsApp (nlHsTyApp return_id [tup_ty]) 
660                               (mk_ret_tup rets)
661
662         mk_wild_pat :: Id -> LPat Id 
663         mk_wild_pat v = noLoc $ WildPat $ idType v
664
665         mk_later_pat :: Id -> LPat Id
666         mk_later_pat v | v `elem` later_ids' = mk_wild_pat v
667                        | otherwise           = nlVarPat v
668
669         mk_tup_pat :: [LPat Id] -> LPat Id
670         mk_tup_pat [p] = p
671         mk_tup_pat ps  = noLoc $ mkVanillaTuplePat ps Boxed
672
673         mk_ret_tup :: [LHsExpr Id] -> LHsExpr Id
674         mk_ret_tup [r] = r
675         mk_ret_tup rs  = noLoc $ ExplicitTuple rs Boxed
676 \end{code}