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