[project @ 2003-06-02 14:26:54 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, mkCoreTupTy, selectMatchVar )
19 import DsMonad
20
21 #ifdef GHCI
22         -- Template Haskell stuff iff bootstrapped
23 import DsMeta           ( dsBracket, dsReify )
24 #endif
25
26 import HsSyn            ( HsExpr(..), Pat(..), ArithSeqInfo(..),
27                           Stmt(..), HsMatchContext(..), HsStmtContext(..), 
28                           Match(..), HsBinds(..), MonoBinds(..), HsConDetails(..),
29                           mkSimpleMatch, isDoExpr
30                         )
31 import TcHsSyn          ( TypecheckedHsExpr, TypecheckedHsBinds, TypecheckedStmt, hsPatType )
32
33 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
34 --     needs to see source types (newtypes etc), and sometimes not
35 --     So WATCH OUT; check each use of split*Ty functions.
36 -- Sigh.  This is a pain.
37
38 import TcType           ( tcSplitAppTy, tcSplitFunTys, tcTyConAppArgs,
39                           tcSplitTyConApp, isUnLiftedType, Type,
40                           mkAppTy )
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, idName, 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 Name             ( Name )
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 dsLet (IPBinds binds is_with) body
91   = foldlDs dsIPBind body binds
92   where
93     dsIPBind body (n, e)
94         = dsExpr e      `thenDs` \ e' ->
95           returnDs (Let (NonRec (ipNameName n) e') body)
96
97 -- Special case for bindings which bind unlifted variables
98 -- We need to do a case right away, rather than building
99 -- a tuple and doing selections.
100 -- Silently ignore INLINE pragmas...
101 dsLet bind@(MonoBind (AbsBinds [] [] exports inlines binds) sigs is_rec) body
102   | or [isUnLiftedType (idType g) | (_, g, l) <- exports]
103   = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
104         -- Unlifted bindings are always non-recursive
105         -- and are always a Fun or Pat monobind
106         --
107         -- ToDo: in some bizarre case it's conceivable that there
108         --       could be dict binds in the 'binds'.  (See the notes
109         --       below.  Then pattern-match would fail.  Urk.)
110     case binds of
111       FunMonoBind fun _ matches loc
112         -> putSrcLocDs loc                              $
113            matchWrapper (FunRhs (idName fun)) matches   `thenDs` \ (args, rhs) ->
114            ASSERT( null args )  -- Functions aren't lifted
115            returnDs (bindNonRec fun rhs body_w_exports)
116
117       PatMonoBind pat grhss loc
118         -> putSrcLocDs loc                      $
119            dsGuarded grhss                      `thenDs` \ rhs ->
120            mk_error_app pat                     `thenDs` \ error_expr ->
121            matchSimply rhs PatBindRhs pat body_w_exports error_expr
122
123       other -> pprPanic "dsLet: unlifted" (ppr bind $$ ppr body)
124   where
125     body_w_exports               = foldr bind_export body exports
126     bind_export (tvs, g, l) body = ASSERT( null tvs )
127                                    bindNonRec g (Var l) body
128
129     mk_error_app pat = mkErrorAppDs iRREFUT_PAT_ERROR_ID
130                                     (exprType body)
131                                     (showSDoc (ppr pat))
132
133 -- Ordinary case for bindings
134 dsLet (MonoBind binds sigs is_rec) body
135   = dsMonoBinds NoSccs binds []  `thenDs` \ prs ->
136     returnDs (Let (Rec prs) body)
137         -- Use a Rec regardless of is_rec. 
138         -- Why? Because it allows the MonoBinds to be all
139         -- mixed up, which is what happens in one rare case
140         -- Namely, for an AbsBind with no tyvars and no dicts,
141         --         but which does have dictionary bindings.
142         -- See notes with TcSimplify.inferLoop [NO TYVARS]
143         -- It turned out that wrapping a Rec here was the easiest solution
144         --
145         -- NB The previous case dealt with unlifted bindings, so we
146         --    only have to deal with lifted ones now; so Rec is ok
147 \end{code}      
148
149 %************************************************************************
150 %*                                                                      *
151 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
152 %*                                                                      *
153 %************************************************************************
154
155 \begin{code}
156 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
157
158 dsExpr (HsPar x) = dsExpr x
159 dsExpr (HsVar var)  = returnDs (Var var)
160 dsExpr (HsIPVar ip) = returnDs (Var (ipNameName ip))
161 dsExpr (HsLit lit)  = dsLit lit
162 -- HsOverLit has been gotten rid of by the type checker
163
164 dsExpr expr@(HsLam a_Match)
165   = matchWrapper LambdaExpr [a_Match]   `thenDs` \ (binders, matching_code) ->
166     returnDs (mkLams binders matching_code)
167
168 dsExpr expr@(HsApp fun arg)      
169   = dsExpr fun          `thenDs` \ core_fun ->
170     dsExpr arg          `thenDs` \ core_arg ->
171     returnDs (core_fun `App` core_arg)
172 \end{code}
173
174 Operator sections.  At first it looks as if we can convert
175 \begin{verbatim}
176         (expr op)
177 \end{verbatim}
178 to
179 \begin{verbatim}
180         \x -> op expr x
181 \end{verbatim}
182
183 But no!  expr might be a redex, and we can lose laziness badly this
184 way.  Consider
185 \begin{verbatim}
186         map (expr op) xs
187 \end{verbatim}
188 for example.  So we convert instead to
189 \begin{verbatim}
190         let y = expr in \x -> op y x
191 \end{verbatim}
192 If \tr{expr} is actually just a variable, say, then the simplifier
193 will sort it out.
194
195 \begin{code}
196 dsExpr (OpApp e1 op _ e2)
197   = dsExpr op                                           `thenDs` \ core_op ->
198     -- for the type of y, we need the type of op's 2nd argument
199     dsExpr e1                           `thenDs` \ x_core ->
200     dsExpr e2                           `thenDs` \ y_core ->
201     returnDs (mkApps core_op [x_core, y_core])
202     
203 dsExpr (SectionL expr op)
204   = dsExpr op                                           `thenDs` \ core_op ->
205     -- for the type of y, we need the type of op's 2nd argument
206     let
207         (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
208         -- Must look through an implicit-parameter type; 
209         -- newtype impossible; hence Type.splitFunTys
210     in
211     dsExpr expr                         `thenDs` \ x_core ->
212     newSysLocalDs x_ty                  `thenDs` \ x_id ->
213     newSysLocalDs y_ty                  `thenDs` \ y_id ->
214
215     returnDs (bindNonRec x_id x_core $
216               Lam y_id (mkApps core_op [Var x_id, Var y_id]))
217
218 -- dsExpr (SectionR op expr)    -- \ x -> op x expr
219 dsExpr (SectionR op expr)
220   = dsExpr op                   `thenDs` \ core_op ->
221     -- for the type of x, we need the type of op's 2nd argument
222     let
223         (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
224         -- See comment with SectionL
225     in
226     dsExpr expr                         `thenDs` \ y_core ->
227     newSysLocalDs x_ty                  `thenDs` \ x_id ->
228     newSysLocalDs y_ty                  `thenDs` \ y_id ->
229
230     returnDs (bindNonRec y_id y_core $
231               Lam x_id (mkApps core_op [Var x_id, Var y_id]))
232
233 dsExpr (HsCCall lbl args may_gc is_asm result_ty)
234   = mapDs dsExpr args           `thenDs` \ core_args ->
235     dsCCall lbl core_args may_gc is_asm result_ty
236         -- dsCCall does all the unboxification, etc.
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   = mapDs 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 mapDs unlabelled_bottom arg_tys
437         else mapDs 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     mapDs 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 (HsReify r)         = dsReify r
559 dsExpr (HsSplice n e _)    = pprPanic "dsExpr:splice" (ppr e)
560 #endif
561
562 \end{code}
563
564
565 \begin{code}
566
567 #ifdef DEBUG
568 -- HsSyn constructs that just shouldn't be here:
569 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
570 dsExpr (ArithSeqIn _)       = panic "dsExpr:ArithSeqIn"
571 dsExpr (PArrSeqIn _)        = panic "dsExpr:PArrSeqIn"
572 #endif
573
574 \end{code}
575
576 %--------------------------------------------------------------------
577
578 Basically does the translation given in the Haskell~1.3 report:
579
580 \begin{code}
581 dsDo    :: HsStmtContext Name
582         -> [TypecheckedStmt]
583         -> [Id]         -- id for: [return,fail,>>=,>>] and possibly mfixName
584         -> Type         -- Element type; the whole expression has type (m t)
585         -> DsM CoreExpr
586
587 dsDo do_or_lc stmts ids result_ty
588   = let
589         (return_id : fail_id : bind_id : then_id : _) = ids
590         (m_ty, b_ty) = tcSplitAppTy result_ty   -- result_ty must be of the form (m b)
591         is_do        = isDoExpr do_or_lc        -- True for both MDo and Do
592         
593         -- For ExprStmt, see the comments near HsExpr.Stmt about 
594         -- exactly what ExprStmts mean!
595         --
596         -- In dsDo we can only see DoStmt and ListComp (no guards)
597
598         go [ResultStmt expr locn]
599           | is_do     = do_expr expr locn
600           | otherwise = do_expr expr locn       `thenDs` \ expr2 ->
601                         returnDs (mkApps (Var return_id) [Type b_ty, expr2])
602
603         go (ExprStmt expr a_ty locn : stmts)
604           | is_do       -- Do expression
605           = do_expr expr locn           `thenDs` \ expr2 ->
606             go stmts                    `thenDs` \ rest  ->
607             returnDs (mkApps (Var then_id) [Type a_ty, Type b_ty, expr2, rest])
608
609            | otherwise  -- List comprehension
610           = do_expr expr locn                   `thenDs` \ expr2 ->
611             go stmts                            `thenDs` \ rest ->
612             let
613                 msg = "Pattern match failure in do expression, " ++ showSDoc (ppr locn)
614             in
615             mkStringLit msg                     `thenDs` \ core_msg ->
616             returnDs (mkIfThenElse expr2 rest 
617                                    (App (App (Var fail_id) (Type b_ty)) core_msg))
618     
619         go (LetStmt binds : stmts )
620           = go stmts            `thenDs` \ rest   ->
621             dsLet binds rest
622             
623         go (BindStmt pat expr locn : stmts)
624           = go stmts                    `thenDs` \ body -> 
625             putSrcLocDs locn            $       -- Rest is associated with this location
626             dsExpr expr                 `thenDs` \ rhs ->
627             mkStringLit (mk_msg locn)   `thenDs` \ core_msg ->
628             let
629                 -- In a do expression, pattern-match failure just calls
630                 -- the monadic 'fail' rather than throwing an exception
631                 fail_expr  = mkApps (Var fail_id) [Type b_ty, core_msg]
632                 a_ty       = hsPatType pat
633             in
634             selectMatchVar pat                                  `thenDs` \ var ->
635             matchSimply (Var var) (StmtCtxt do_or_lc) pat
636                         body fail_expr                          `thenDs` \ match_code ->
637             returnDs (mkApps (Var bind_id) [Type a_ty, Type b_ty, rhs, Lam var match_code])
638
639         go (RecStmt rec_vars rec_stmts rec_rets : stmts)
640           = go (bind_stmt : stmts)
641           where
642             bind_stmt = dsRecStmt m_ty ids rec_vars rec_stmts rec_rets
643             
644     in
645     go stmts
646
647   where
648     do_expr expr locn = putSrcLocDs locn (dsExpr expr)
649     mk_msg locn = "Pattern match failure in do expression at " ++ showSDoc (ppr locn)
650 \end{code}
651
652 Translation for RecStmt's: 
653 -----------------------------
654 We turn (RecStmt [v1,..vn] stmts) into:
655   
656   (v1,..,vn) <- mfix (\~(v1,..vn). do stmts
657                                       return (v1,..vn))
658
659 \begin{code}
660 dsRecStmt :: Type               -- Monad type constructor :: * -> *
661           -> [Id]               -- Ids for: [return,fail,>>=,>>,mfix]
662           -> [Id] -> [TypecheckedStmt]  -> [TypecheckedHsExpr]  -- Guts of the RecStmt
663           -> TypecheckedStmt
664 dsRecStmt m_ty ids@[return_id, _, _, _, mfix_id] vars stmts rets
665   = ASSERT( length vars == length rets )
666     BindStmt tup_pat mfix_app noSrcLoc
667   where 
668         (var1:rest) = vars              -- Always at least one
669         (ret1:_)    = rets
670         one_var     = null rest
671
672         mfix_app = HsApp (TyApp (HsVar mfix_id) [tup_ty]) mfix_arg
673         mfix_arg = HsLam (mkSimpleMatch [tup_pat] body tup_ty noSrcLoc)
674
675         tup_expr | one_var   = ret1
676                  | otherwise = ExplicitTuple rets Boxed
677         tup_ty               = mkCoreTupTy (map idType vars)
678                                         -- Deals with singleton case
679         tup_pat  | one_var   = VarPat var1
680                  | otherwise = LazyPat (TuplePat (map VarPat vars) Boxed)
681
682         body = HsDo DoExpr (stmts ++ [return_stmt]) 
683                            ids  -- Don't need the mfix, but it does no harm
684                            (mkAppTy m_ty tup_ty)
685                            noSrcLoc
686
687         return_stmt = ResultStmt return_app noSrcLoc
688         return_app  = HsApp (TyApp (HsVar return_id) [tup_ty]) tup_expr
689 \end{code}