BugFix: do not insert breakpoints around expressions with unlifted kind
[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 module DsExpr ( dsExpr, dsLExpr, dsLocalBinds, dsValBinds, dsLit ) where
10
11 #include "HsVersions.h"
12
13
14 import Match
15 import MatchLit
16 import DsBinds
17 import DsGRHSs
18 import DsListComp
19 import DsUtils
20 import DsArrows
21 import DsMonad
22
23 #ifdef GHCI
24 import PrelNames
25 import DsBreakpoint
26         -- Template Haskell stuff iff bootstrapped
27 import DsMeta
28 #else
29 import DsBreakpoint
30 #endif
31
32 import HsSyn
33 import TcHsSyn
34
35 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
36 --     needs to see source types
37 import TcType
38 import Type
39 import CoreSyn
40 import CoreUtils
41
42 import CostCentre
43 import Id
44 import PrelInfo
45 import DataCon
46 import TyCon
47 import TysWiredIn
48 import BasicTypes
49 import PrelNames
50 import SrcLoc
51 import Util
52 import Bag
53 import Outputable
54 import FastString
55
56 import Data.Maybe
57 \end{code}
58
59
60 %************************************************************************
61 %*                                                                      *
62                 dsLocalBinds, dsValBinds
63 %*                                                                      *
64 %************************************************************************
65
66 \begin{code}
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
71
72 -------------------------
73 dsValBinds :: HsValBinds Id -> CoreExpr -> DsM CoreExpr
74 dsValBinds (ValBindsOut binds _) body = foldrDs ds_val_bind body binds
75
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 }
83   where
84     ds_ip_bind (L _ (IPBind n e)) body
85       = dsLExpr e       `thenDs` \ e' ->
86         returnDs (Let (NonRec (ipNameName n) e') body)
87
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,
97     isBangHsBind bind
98     || isUnboxedTupleBind bind
99     || or [isUnLiftedType (idType g) | (_, g, _, _) <- exports]
100   = let
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
104     in
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.)
110     putSrcSpanDs loc    $
111     case bind of
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)
118
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
122            putSrcSpanDs loc                     $
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) }
130
131       other -> pprPanic "dsLet: unlifted" (pprLHsBinds hsbinds $$ ppr body)
132
133
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) )
138           case prs of
139             []    -> return body
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
148         --
149         -- NB The previous case dealt with unlifted bindings, so we
150         --    only have to deal with lifted ones now; so Rec is ok
151
152 isUnboxedTupleBind :: HsBind Id -> Bool
153 isUnboxedTupleBind (PatBind { pat_rhs_ty = ty }) = isUnboxedTupleType ty
154 isUnboxedTupleBind other                         = False
155
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
160 -- The idea is that 
161 --      case e of (# p1, p2 #) -> rhs
162 -- should desugar to
163 --      case e of (# x1, x2 #) -> ... match p1, p2 ...
164 -- NOT
165 --      let x = e in case x of ....
166 --
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.
171
172 scrungleMatch var scrut body
173   | isUnboxedTupleType (idType var) = scrungle body
174   | otherwise                       = bindNonRec var scrut body
175   where
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))
180
181 \end{code}      
182
183 %************************************************************************
184 %*                                                                      *
185 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
186 %*                                                                      *
187 %************************************************************************
188
189 \begin{code}
190 dsLExpr :: LHsExpr Id -> DsM CoreExpr
191
192 #if defined(GHCI)
193 dsLExpr (L loc expr@(HsWrap w (HsVar v)))
194     | idName v `elem` [breakpointName, breakpointCondName, breakpointAutoName]
195     = do areBreakpointsEnabled <- breakpoints_enabled
196          if areBreakpointsEnabled
197            then do
198               L _ breakpointExpr <- mkBreakpointExpr loc v
199               dsLExpr (L loc $ HsWrap w breakpointExpr)
200            else putSrcSpanDs loc $ dsExpr expr
201 #endif
202
203 dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e
204
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)
213
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) }
218
219 dsExpr expr@(HsLam a_Match)
220   = matchWrapper LambdaExpr a_Match     `thenDs` \ (binders, matching_code) ->
221     returnDs (mkLams binders matching_code)
222
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)
227 \end{code}
228
229 Operator sections.  At first it looks as if we can convert
230 \begin{verbatim}
231         (expr op)
232 \end{verbatim}
233 to
234 \begin{verbatim}
235         \x -> op expr x
236 \end{verbatim}
237
238 But no!  expr might be a redex, and we can lose laziness badly this
239 way.  Consider
240 \begin{verbatim}
241         map (expr op) xs
242 \end{verbatim}
243 for example.  So we convert instead to
244 \begin{verbatim}
245         let y = expr in \x -> op y x
246 \end{verbatim}
247 If \tr{expr} is actually just a variable, say, then the simplifier
248 will sort it out.
249
250 \begin{code}
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])
257     
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)
262
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
267     let
268         (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
269         -- See comment with SectionL
270     in
271     dsLExpr expr                                `thenDs` \ y_core ->
272     newSysLocalDs x_ty                  `thenDs` \ x_id ->
273     newSysLocalDs y_ty                  `thenDs` \ y_id ->
274
275     returnDs (bindNonRec y_id y_core $
276               Lam x_id (mkApps core_op [Var x_id, Var y_id]))
277
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)
282
283
284 -- hdaume: core annotation
285
286 dsExpr (HsCoreAnn fs expr)
287   = dsLExpr expr        `thenDs` \ core_expr ->
288     returnDs (Note (CoreNote $ unpackFS fs) core_expr)
289
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)
294
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'
301
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.
304 --
305 dsExpr (HsDo ListComp stmts body result_ty)
306   =     -- Special case for list comprehensions
307     dsListComp stmts body elt_ty
308   where
309     [elt_ty] = tcTyConAppArgs result_ty
310
311 dsExpr (HsDo DoExpr stmts body result_ty)
312   = dsDo stmts body result_ty
313
314 dsExpr (HsDo (MDoExpr tbl) stmts body result_ty)
315   = dsMDo tbl stmts body result_ty
316
317 dsExpr (HsDo PArrComp stmts body result_ty)
318   =     -- Special case for array comprehensions
319     dsPArrComp (map unLoc stmts) body elt_ty
320   where
321     [elt_ty] = tcTyConAppArgs result_ty
322
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)
328 \end{code}
329
330
331 \noindent
332 \underline{\bf Various data construction things}
333 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
334 \begin{code}
335 dsExpr (ExplicitList ty xs)
336   = go xs
337   where
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)
342
343 -- we create a list from the array elements and convert them into a list using
344 -- `PrelPArr.toP'
345 --
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
352 --
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])
357
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))
362
363 dsExpr (ArithSeq expr (From from))
364   = dsExpr expr           `thenDs` \ expr2 ->
365     dsLExpr from          `thenDs` \ from2 ->
366     returnDs (App expr2 from2)
367
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])
373
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])
379
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])
386
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])
392
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])
399
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
404 \end{code}
405
406 \noindent
407 \underline{\bf Record construction and update}
408 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
409 For record construction we do this (assuming T has three arguments)
410 \begin{verbatim}
411         T { op2 = e }
412 ==>
413         let err = /\a -> recConErr a 
414         T (recConErr t1 "M.lhs/230/op1") 
415           e 
416           (recConErr t1 "M.lhs/230/op3")
417 \end{verbatim}
418 @recConErr@ then converts its arugment string into a proper message
419 before printing it as
420 \begin{verbatim}
421         M.lhs, line 230: missing field op1 was evaluated
422 \end{verbatim}
423
424 We also handle @C{}@ as valid construction syntax for an unlabelled
425 constructor @C@, setting all of @C@'s fields to bottom.
426
427 \begin{code}
428 dsExpr (RecordCon (L _ data_con_id) con_expr rbinds)
429   = dsExpr con_expr     `thenDs` \ con_expr' ->
430     let
431         (arg_tys, _) = tcSplitFunTys (exprType con_expr')
432         -- A newtype in the corner should be opaque; 
433         -- hence TcType.tcSplitFunTys
434
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 )
438                             dsLExpr rhs
439               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
440         unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
441
442         labels = dataConFieldLabels (idDataCon data_con_id)
443         -- The data_con_id is guaranteed to be the wrapper id of the constructor
444     in
445
446     (if null labels
447         then mappM unlabelled_bottom arg_tys
448         else mappM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
449         `thenDs` \ con_args ->
450
451     returnDs (mkApps con_expr' con_args)
452 \end{code}
453
454 Record update is a little harder. Suppose we have the decl:
455 \begin{verbatim}
456         data T = T1 {op1, op2, op3 :: Int}
457                | T2 {op4, op2 :: Int}
458                | T3
459 \end{verbatim}
460 Then we translate as follows:
461 \begin{verbatim}
462         r { op2 = e }
463 ===>
464         let op2 = e in
465         case r of
466           T1 op1 _ op3 -> T1 op1 op2 op3
467           T2 op4 _     -> T2 op4 op2
468           other        -> recUpdError "M.lhs/230"
469 \end{verbatim}
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
473 dictionaries.
474
475 \begin{code}
476 dsExpr (RecordUpd record_expr [] record_in_ty record_out_ty)
477   = dsLExpr record_expr
478
479 dsExpr expr@(RecordUpd record_expr rbinds record_in_ty record_out_ty)
480   = dsLExpr record_expr         `thenDs` \ record_expr' ->
481
482         -- Desugar the rbinds, and generate let-bindings if
483         -- necessary so that we don't lose sharing
484
485     let
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
489
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
494
495         mk_alt con
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
500             let 
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)
505                             val_args
506             in
507             returnDs (mkSimpleMatch [mkPrefixConPat con (map nlVarPat arg_ids) record_in_ty] rhs)
508     in
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 )
513
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) ->
520
521     returnDs (bindNonRec discrim_var record_expr' matching_code)
522
523   where
524     updated_fields :: [FieldLabel]
525     updated_fields = [ idName sel_id | (L _ sel_id,_) <- rbinds]
526
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
534
535     has_all_fields :: DataCon -> Bool
536     has_all_fields con_id 
537       = all (`elem` con_fields) updated_fields
538       where
539         con_fields = dataConFieldLabels con_id
540 \end{code}
541
542 Here is where we desugar the Template Haskell brackets and escapes
543
544 \begin{code}
545 -- Template Haskell stuff
546
547 #ifdef GHCI     /* Only if bootstrapping */
548 dsExpr (HsBracketOut x ps) = dsBracket x ps
549 dsExpr (HsSpliceE s)       = pprPanic "dsExpr:splice" (ppr s)
550 #endif
551
552 -- Arrow notation extension
553 dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
554 \end{code}
555
556 Hpc Support 
557
558 \begin{code}
559 dsExpr (HsTick ix e) = do
560   e' <- dsLExpr e
561   mkTickBox ix e'
562
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
568 -- tick counting.
569
570 dsExpr (HsBinTick ixT ixF e) = do
571   e2 <- dsLExpr e
572   do { ASSERT(exprType e2 `coreEqType` boolTy)
573        mkBinaryTickBox ixT ixF e2
574      }
575 \end{code}
576
577 \begin{code}
578
579 #ifdef DEBUG
580 -- HsSyn constructs that just shouldn't be here:
581 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
582 #endif
583
584 \end{code}
585
586 %--------------------------------------------------------------------
587
588 Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
589 handled in DsListComp).  Basically does the translation given in the
590 Haskell 98 report:
591
592 \begin{code}
593 dsDo    :: [LStmt Id]
594         -> LHsExpr Id
595         -> Type                 -- Type of the whole expression
596         -> DsM CoreExpr
597
598 dsDo stmts body result_ty
599   = go (map unLoc stmts)
600   where
601     go [] = dsAndThenMaybeInsertBreakpoint body
602     
603     go (ExprStmt rhs then_expr _ : stmts)
604       = do { rhs2 <- dsAndThenMaybeInsertBreakpoint rhs
605            ; then_expr2 <- dsExpr then_expr
606            ; rest <- go stmts
607            ; returnDs (mkApps then_expr2 [rhs2, rest]) }
608     
609     go (LetStmt binds : stmts)
610       = do { rest <- bindLocalsDs (map unLoc$ collectLocalBinders binds) $ 
611                       go stmts
612            ; dsLocalBinds binds rest }
613
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)
618       = 
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]) }
627     
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
631       | matchCanFail match
632       = do { fail_op' <- dsExpr fail_op
633            ; fail_msg <- mkStringExpr (mk_fail_msg pat)
634            ; extractMatchResult match (App fail_op' fail_msg) }
635       | otherwise
636       = extractMatchResult match (error "It can't fail") 
637
638 mk_fail_msg pat = "Pattern match failure in do expression at " ++ 
639                   showSDoc (ppr (getLoc pat))
640 \end{code}
641
642 Translation for RecStmt's: 
643 -----------------------------
644 We turn (RecStmt [v1,..vn] stmts) into:
645   
646   (v1,..,vn) <- mfix (\~(v1,..vn). do stmts
647                                       return (v1,..vn))
648
649 \begin{code}
650 dsMDo   :: PostTcTable
651         -> [LStmt Id]
652         -> LHsExpr Id
653         -> Type                 -- Type of the whole expression
654         -> DsM CoreExpr
655
656 dsMDo tbl stmts body result_ty
657   = go (map unLoc stmts)
658   where
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
665     ctxt      = MDoExpr tbl
666
667     go [] = dsLExpr body
668     
669     go (LetStmt binds : stmts)
670       = do { rest <- go stmts
671            ; dsLocalBinds binds rest }
672
673     go (ExprStmt rhs _ rhs_ty : stmts)
674       = do { rhs2 <- dsAndThenMaybeInsertBreakpoint rhs
675            ; rest <- go stmts
676            ; returnDs (mkApps (Var then_id) [Type rhs_ty, Type b_ty, rhs2, rest]) }
677     
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
686
687            ; rhs'       <- dsAndThenMaybeInsertBreakpoint rhs
688            ; returnDs (mkApps (Var bind_id) [Type (hsLPatType pat), Type b_ty, 
689                                              rhs', Lam var match_code]) }
690     
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)
695       where
696         new_bind_stmt = mkBindStmt (mk_tup_pat later_pats) mfix_app
697         let_stmt = LetStmt (HsValBinds (ValBindsOut [(Recursive, binds)] []))
698
699         
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 ]
705     
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))
709
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
716
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
722
723         return_app  = nlHsApp (nlHsTyApp return_id [tup_ty]) 
724                               (mk_ret_tup rets)
725
726         mk_wild_pat :: Id -> LPat Id 
727         mk_wild_pat v = noLoc $ WildPat $ idType v
728
729         mk_later_pat :: Id -> LPat Id
730         mk_later_pat v | v `elem` later_ids' = mk_wild_pat v
731                        | otherwise           = nlVarPat v
732
733         mk_tup_pat :: [LPat Id] -> LPat Id
734         mk_tup_pat [p] = p
735         mk_tup_pat ps  = noLoc $ mkVanillaTuplePat ps Boxed
736
737         mk_ret_tup :: [LHsExpr Id] -> LHsExpr Id
738         mk_ret_tup [r] = r
739         mk_ret_tup rs  = noLoc $ ExplicitTuple rs Boxed
740 \end{code}