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