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