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