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