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