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