cedb95f79d09e431c4ee8382240a68ca22e2a51d
[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 x) = dsLExpr x
160 dsExpr (HsVar var)  = returnDs (Var var)
161 dsExpr (HsIPVar ip) = returnDs (Var (ipNameName ip))
162 dsExpr (HsLit lit)  = dsLit lit
163 -- HsOverLit has been gotten rid of by the type checker
164
165 dsExpr expr@(HsLam a_Match)
166   = matchWrapper LambdaExpr [a_Match]   `thenDs` \ (binders, matching_code) ->
167     returnDs (mkLams binders matching_code)
168
169 dsExpr expr@(HsApp fun arg)      
170   = dsLExpr fun         `thenDs` \ core_fun ->
171     dsLExpr arg         `thenDs` \ core_arg ->
172     returnDs (core_fun `App` core_arg)
173 \end{code}
174
175 Operator sections.  At first it looks as if we can convert
176 \begin{verbatim}
177         (expr op)
178 \end{verbatim}
179 to
180 \begin{verbatim}
181         \x -> op expr x
182 \end{verbatim}
183
184 But no!  expr might be a redex, and we can lose laziness badly this
185 way.  Consider
186 \begin{verbatim}
187         map (expr op) xs
188 \end{verbatim}
189 for example.  So we convert instead to
190 \begin{verbatim}
191         let y = expr in \x -> op y x
192 \end{verbatim}
193 If \tr{expr} is actually just a variable, say, then the simplifier
194 will sort it out.
195
196 \begin{code}
197 dsExpr (OpApp e1 op _ e2)
198   = dsLExpr op                                          `thenDs` \ core_op ->
199     -- for the type of y, we need the type of op's 2nd argument
200     dsLExpr e1                          `thenDs` \ x_core ->
201     dsLExpr e2                          `thenDs` \ y_core ->
202     returnDs (mkApps core_op [x_core, y_core])
203     
204 dsExpr (SectionL expr op)
205   = dsLExpr op                                          `thenDs` \ core_op ->
206     -- for the type of y, we need the type of op's 2nd argument
207     let
208         (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
209         -- Must look through an implicit-parameter type; 
210         -- newtype impossible; hence Type.splitFunTys
211     in
212     dsLExpr expr                                `thenDs` \ x_core ->
213     newSysLocalDs x_ty                  `thenDs` \ x_id ->
214     newSysLocalDs y_ty                  `thenDs` \ y_id ->
215
216     returnDs (bindNonRec x_id x_core $
217               Lam y_id (mkApps core_op [Var x_id, Var y_id]))
218
219 -- dsLExpr (SectionR op expr)   -- \ x -> op x expr
220 dsExpr (SectionR op expr)
221   = dsLExpr op                  `thenDs` \ core_op ->
222     -- for the type of x, we need the type of op's 2nd argument
223     let
224         (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
225         -- See comment with SectionL
226     in
227     dsLExpr expr                                `thenDs` \ y_core ->
228     newSysLocalDs x_ty                  `thenDs` \ x_id ->
229     newSysLocalDs y_ty                  `thenDs` \ y_id ->
230
231     returnDs (bindNonRec y_id y_core $
232               Lam x_id (mkApps core_op [Var x_id, Var y_id]))
233
234 dsExpr (HsSCC cc expr)
235   = dsLExpr expr                        `thenDs` \ core_expr ->
236     getModuleDs                 `thenDs` \ mod_name ->
237     returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
238
239
240 -- hdaume: core annotation
241
242 dsExpr (HsCoreAnn fs expr)
243   = dsLExpr expr        `thenDs` \ core_expr ->
244     returnDs (Note (CoreNote $ unpackFS fs) core_expr)
245
246 -- special case to handle unboxed tuple patterns.
247
248 dsExpr (HsCase discrim matches)
249  | all ubx_tuple_match matches
250  =  dsLExpr discrim                     `thenDs` \ core_discrim ->
251     matchWrapper CaseAlt matches        `thenDs` \ ([discrim_var], matching_code) ->
252     case matching_code of
253         Case (Var x) bndr alts | x == discrim_var -> 
254                 returnDs (Case core_discrim bndr alts)
255         _ -> panic ("dsLExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
256   where
257     ubx_tuple_match (L _ (Match [L _ (TuplePat _ Unboxed)] _ _)) = True
258     ubx_tuple_match _ = False
259
260 dsExpr (HsCase discrim matches)
261   = dsLExpr discrim                     `thenDs` \ core_discrim ->
262     matchWrapper CaseAlt matches        `thenDs` \ ([discrim_var], matching_code) ->
263     returnDs (bindNonRec discrim_var core_discrim matching_code)
264
265 dsExpr (HsLet binds body)
266   = dsLExpr body                `thenDs` \ body' ->
267     dsLet binds body'
268
269 -- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
270 -- because the interpretation of `stmts' depends on what sort of thing it is.
271 --
272 dsExpr (HsDo ListComp stmts _ result_ty)
273   =     -- Special case for list comprehensions
274     dsListComp stmts elt_ty
275   where
276     (_, [elt_ty]) = tcSplitTyConApp result_ty
277
278 dsExpr (HsDo do_or_lc stmts ids result_ty)
279   | isDoExpr do_or_lc
280   = dsDo do_or_lc stmts ids result_ty
281
282 dsExpr (HsDo PArrComp stmts _ result_ty)
283   =     -- Special case for array comprehensions
284     dsPArrComp (map unLoc stmts) elt_ty
285   where
286     (_, [elt_ty]) = tcSplitTyConApp result_ty
287
288 dsExpr (HsIf guard_expr then_expr else_expr)
289   = dsLExpr guard_expr  `thenDs` \ core_guard ->
290     dsLExpr then_expr   `thenDs` \ core_then ->
291     dsLExpr else_expr   `thenDs` \ core_else ->
292     returnDs (mkIfThenElse core_guard core_then core_else)
293 \end{code}
294
295
296 \noindent
297 \underline{\bf Type lambda and application}
298 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~
299 \begin{code}
300 dsExpr (TyLam tyvars expr)
301   = dsLExpr expr `thenDs` \ core_expr ->
302     returnDs (mkLams tyvars core_expr)
303
304 dsExpr (TyApp expr tys)
305   = dsLExpr expr                `thenDs` \ core_expr ->
306     returnDs (mkTyApps core_expr tys)
307 \end{code}
308
309
310 \noindent
311 \underline{\bf Various data construction things}
312 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
313 \begin{code}
314 dsExpr (ExplicitList ty xs)
315   = go xs
316   where
317     go []     = returnDs (mkNilExpr ty)
318     go (x:xs) = dsLExpr x                               `thenDs` \ core_x ->
319                 go xs                                   `thenDs` \ core_xs ->
320                 returnDs (mkConsExpr ty core_x core_xs)
321
322 -- we create a list from the array elements and convert them into a list using
323 -- `PrelPArr.toP'
324 --
325 -- * the main disadvantage to this scheme is that `toP' traverses the list
326 --   twice: once to determine the length and a second time to put to elements
327 --   into the array; this inefficiency could be avoided by exposing some of
328 --   the innards of `PrelPArr' to the compiler (ie, have a `PrelPArrBase') so
329 --   that we can exploit the fact that we already know the length of the array
330 --   here at compile time
331 --
332 dsExpr (ExplicitPArr ty xs)
333   = dsLookupGlobalId toPName                            `thenDs` \toP      ->
334     dsExpr (ExplicitList ty xs)                         `thenDs` \coreList ->
335     returnDs (mkApps (Var toP) [Type ty, coreList])
336
337 dsExpr (ExplicitTuple expr_list boxity)
338   = mappM dsLExpr expr_list       `thenDs` \ core_exprs  ->
339     returnDs (mkConApp (tupleCon boxity (length expr_list))
340                        (map (Type .  exprType) core_exprs ++ core_exprs))
341
342 dsExpr (ArithSeqOut expr (From from))
343   = dsLExpr expr                  `thenDs` \ expr2 ->
344     dsLExpr from                  `thenDs` \ from2 ->
345     returnDs (App expr2 from2)
346
347 dsExpr (ArithSeqOut expr (FromTo from two))
348   = dsLExpr expr                  `thenDs` \ expr2 ->
349     dsLExpr from                  `thenDs` \ from2 ->
350     dsLExpr two           `thenDs` \ two2 ->
351     returnDs (mkApps expr2 [from2, two2])
352
353 dsExpr (ArithSeqOut expr (FromThen from thn))
354   = dsLExpr expr                  `thenDs` \ expr2 ->
355     dsLExpr from                  `thenDs` \ from2 ->
356     dsLExpr thn           `thenDs` \ thn2 ->
357     returnDs (mkApps expr2 [from2, thn2])
358
359 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
360   = dsLExpr expr                  `thenDs` \ expr2 ->
361     dsLExpr from                  `thenDs` \ from2 ->
362     dsLExpr thn           `thenDs` \ thn2 ->
363     dsLExpr two           `thenDs` \ two2 ->
364     returnDs (mkApps expr2 [from2, thn2, two2])
365
366 dsExpr (PArrSeqOut expr (FromTo from two))
367   = dsLExpr expr                  `thenDs` \ expr2 ->
368     dsLExpr from                  `thenDs` \ from2 ->
369     dsLExpr two           `thenDs` \ two2 ->
370     returnDs (mkApps expr2 [from2, two2])
371
372 dsExpr (PArrSeqOut expr (FromThenTo from thn two))
373   = dsLExpr expr                  `thenDs` \ expr2 ->
374     dsLExpr from                  `thenDs` \ from2 ->
375     dsLExpr thn           `thenDs` \ thn2 ->
376     dsLExpr two           `thenDs` \ two2 ->
377     returnDs (mkApps expr2 [from2, thn2, two2])
378
379 dsExpr (PArrSeqOut expr _)
380   = panic "DsExpr.dsExpr: Infinite parallel array!"
381     -- the parser shouldn't have generated it and the renamer and typechecker
382     -- shouldn't have let it through
383 \end{code}
384
385 \noindent
386 \underline{\bf Record construction and update}
387 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
388 For record construction we do this (assuming T has three arguments)
389 \begin{verbatim}
390         T { op2 = e }
391 ==>
392         let err = /\a -> recConErr a 
393         T (recConErr t1 "M.lhs/230/op1") 
394           e 
395           (recConErr t1 "M.lhs/230/op3")
396 \end{verbatim}
397 @recConErr@ then converts its arugment string into a proper message
398 before printing it as
399 \begin{verbatim}
400         M.lhs, line 230: missing field op1 was evaluated
401 \end{verbatim}
402
403 We also handle @C{}@ as valid construction syntax for an unlabelled
404 constructor @C@, setting all of @C@'s fields to bottom.
405
406 \begin{code}
407 dsExpr (RecordConOut data_con con_expr rbinds)
408   = dsLExpr con_expr    `thenDs` \ con_expr' ->
409     let
410         (arg_tys, _) = tcSplitFunTys (exprType con_expr')
411         -- A newtype in the corner should be opaque; 
412         -- hence TcType.tcSplitFunTys
413
414         mk_arg (arg_ty, lbl)
415           = case [rhs | (L _ sel_id, rhs) <- rbinds,
416                         lbl == recordSelectorFieldLabel sel_id] of
417               (rhs:rhss) -> ASSERT( null rhss )
418                             dsLExpr rhs
419               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
420         unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
421
422         labels = dataConFieldLabels data_con
423     in
424
425     (if null labels
426         then mappM unlabelled_bottom arg_tys
427         else mappM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
428         `thenDs` \ con_args ->
429
430     returnDs (mkApps con_expr' con_args)
431 \end{code}
432
433 Record update is a little harder. Suppose we have the decl:
434 \begin{verbatim}
435         data T = T1 {op1, op2, op3 :: Int}
436                | T2 {op4, op2 :: Int}
437                | T3
438 \end{verbatim}
439 Then we translate as follows:
440 \begin{verbatim}
441         r { op2 = e }
442 ===>
443         let op2 = e in
444         case r of
445           T1 op1 _ op3 -> T1 op1 op2 op3
446           T2 op4 _     -> T2 op4 op2
447           other        -> recUpdError "M.lhs/230"
448 \end{verbatim}
449 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
450 RHSs, and do not generate a Core constructor application directly, because the constructor
451 might do some argument-evaluation first; and may have to throw away some
452 dictionaries.
453
454 \begin{code}
455 dsExpr (RecordUpdOut record_expr record_in_ty record_out_ty [])
456   = dsLExpr record_expr
457
458 dsExpr expr@(RecordUpdOut record_expr record_in_ty record_out_ty rbinds)
459   = dsLExpr record_expr         `thenDs` \ record_expr' ->
460
461         -- Desugar the rbinds, and generate let-bindings if
462         -- necessary so that we don't lose sharing
463
464     let
465         in_inst_tys  = tcTyConAppArgs record_in_ty      -- Newtype opaque
466         out_inst_tys = tcTyConAppArgs record_out_ty     -- Newtype opaque
467
468         mk_val_arg field old_arg_id 
469           = case [rhs | (L _ sel_id, rhs) <- rbinds, 
470                         field == recordSelectorFieldLabel sel_id] of
471               (rhs:rest) -> ASSERT(null rest) rhs
472               []         -> nlHsVar old_arg_id
473
474         mk_alt con
475           = newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
476                 -- This call to dataConArgTys won't work for existentials
477             let 
478                 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
479                                         (dataConFieldLabels con) arg_ids
480                 rhs = foldl (\a b -> nlHsApp a b)
481                         (noLoc $ TyApp (nlHsVar (dataConWrapId con)) 
482                                 out_inst_tys)
483                           val_args
484             in
485             returnDs (mkSimpleMatch [noLoc $ ConPatOut con (PrefixCon (map nlVarPat arg_ids)) record_in_ty [] []]
486                                     rhs
487                                     record_out_ty)
488     in
489         -- Record stuff doesn't work for existentials
490         -- The type checker checks for this, but we need 
491         -- worry only about the constructors that are to be updated
492     ASSERT2( all (not . isExistentialDataCon) cons_to_upd, ppr expr )
493
494         -- It's important to generate the match with matchWrapper,
495         -- and the right hand sides with applications of the wrapper Id
496         -- so that everything works when we are doing fancy unboxing on the
497         -- constructor aguments.
498     mappM mk_alt cons_to_upd            `thenDs` \ alts ->
499     matchWrapper RecUpd alts            `thenDs` \ ([discrim_var], matching_code) ->
500
501     returnDs (bindNonRec discrim_var record_expr' matching_code)
502
503   where
504     updated_fields :: [FieldLabel]
505     updated_fields = [ recordSelectorFieldLabel sel_id 
506                      | (L _ sel_id,_) <- rbinds]
507
508         -- Get the type constructor from the first field label, 
509         -- so that we are sure it'll have all its DataCons
510         -- (In GHCI, it's possible that some TyCons may not have all
511         --  their constructors, in a module-loop situation.)
512     tycon       = fieldLabelTyCon (head updated_fields)
513     data_cons   = tyConDataCons tycon
514     cons_to_upd = filter has_all_fields data_cons
515
516     has_all_fields :: DataCon -> Bool
517     has_all_fields con_id 
518       = all (`elem` con_fields) updated_fields
519       where
520         con_fields = dataConFieldLabels con_id
521 \end{code}
522
523
524 \noindent
525 \underline{\bf Dictionary lambda and application}
526 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
527 @DictLam@ and @DictApp@ turn into the regular old things.
528 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
529 complicated; reminiscent of fully-applied constructors.
530 \begin{code}
531 dsExpr (DictLam dictvars expr)
532   = dsLExpr expr `thenDs` \ core_expr ->
533     returnDs (mkLams dictvars core_expr)
534
535 ------------------
536
537 dsExpr (DictApp expr dicts)     -- becomes a curried application
538   = dsLExpr expr                        `thenDs` \ core_expr ->
539     returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
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
557 \begin{code}
558
559 #ifdef DEBUG
560 -- HsSyn constructs that just shouldn't be here:
561 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
562 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
563 dsExpr (PArrSeqIn _)        = panic "dsExpr:PArrSeqIn"
564 #endif
565
566 \end{code}
567
568 %--------------------------------------------------------------------
569
570 Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
571 handled in DsListComp).  Basically does the translation given in the
572 Haskell 98 report:
573
574 \begin{code}
575 dsDo    :: HsStmtContext Name
576         -> [LStmt Id]
577         -> ReboundNames Id      -- id for: [return,fail,>>=,>>] and possibly mfixName
578         -> Type                 -- Element type; the whole expression has type (m t)
579         -> DsM CoreExpr
580
581 dsDo do_or_lc stmts ids result_ty
582   = dsReboundNames ids          `thenDs` \ (meth_binds, ds_meths) ->
583     let
584         return_id = lookupReboundName ds_meths returnMName
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}