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