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