[project @ 2005-07-19 16:44: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, dsLExpr, dsLocalBinds, dsValBinds, dsLit ) where
8
9 #include "HsVersions.h"
10
11
12 import Match            ( matchWrapper, matchSimply, matchSinglePat )
13 import MatchLit         ( dsLit, dsOverLit )
14 import DsBinds          ( dsLHsBinds )
15 import DsGRHSs          ( dsGuarded )
16 import DsListComp       ( dsListComp, dsPArrComp )
17 import DsUtils          ( mkErrorAppDs, mkStringExpr, mkConsExpr, mkNilExpr,
18                           extractMatchResult, cantFailMatchResult, matchCanFail,
19                           mkCoreTupTy, selectSimpleMatchVarL, lookupEvidence )
20 import DsArrows         ( dsProcExpr )
21 import DsMonad
22
23 #ifdef GHCI
24         -- Template Haskell stuff iff bootstrapped
25 import DsMeta           ( dsBracket )
26 #endif
27
28 import HsSyn
29 import TcHsSyn          ( hsPatType )
30
31 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
32 --     needs to see source types (newtypes etc), and sometimes not
33 --     So WATCH OUT; check each use of split*Ty functions.
34 -- Sigh.  This is a pain.
35
36 import TcType           ( tcSplitAppTy, tcSplitFunTys, tcTyConAppTyCon, 
37                           tcTyConAppArgs, isUnLiftedType, Type, mkAppTy )
38 import Type             ( funArgTy, splitFunTys, isUnboxedTupleType, mkFunTy )
39 import CoreSyn
40 import CoreUtils        ( exprType, mkIfThenElse, bindNonRec )
41
42 import CostCentre       ( mkUserCC )
43 import Id               ( Id, idType, idName, idDataCon )
44 import PrelInfo         ( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
45 import DataCon          ( DataCon, dataConWrapId, dataConFieldLabels, dataConInstOrigArgTys )
46 import DataCon          ( isVanillaDataCon )
47 import TyCon            ( FieldLabel, tyConDataCons )
48 import TysWiredIn       ( tupleCon )
49 import BasicTypes       ( RecFlag(..), Boxity(..), ipNameName )
50 import PrelNames        ( toPName,
51                           returnMName, bindMName, thenMName, failMName,
52                           mfixName )
53 import SrcLoc           ( Located(..), unLoc, getLoc, noLoc )
54 import Util             ( zipEqual, zipWithEqual )
55 import Bag              ( bagToList )
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 dsLocalBinds :: HsLocalBinds Id -> CoreExpr -> DsM CoreExpr
80 dsLocalBinds EmptyLocalBinds    body = return body
81 dsLocalBinds (HsValBinds binds) body = dsValBinds binds body
82 dsLocalBinds (HsIPBinds binds)  body = dsIPBinds  binds body
83
84 -------------------------
85 dsValBinds :: HsValBinds Id -> CoreExpr -> DsM CoreExpr
86 dsValBinds (ValBindsOut binds) body = foldrDs ds_val_bind body binds
87
88 -------------------------
89 dsIPBinds (IPBinds ip_binds dict_binds) body
90   = do  { prs <- dsLHsBinds dict_binds
91         ; let inner = foldr (\(x,r) e -> Let (NonRec x r) e) body prs 
92         ; foldrDs ds_ip_bind inner ip_binds }
93   where
94     ds_ip_bind (L _ (IPBind n e)) body
95       = dsLExpr e       `thenDs` \ e' ->
96         returnDs (Let (NonRec (ipNameName n) e') body)
97
98 -------------------------
99 ds_val_bind :: (RecFlag, LHsBinds Id) -> CoreExpr -> DsM CoreExpr
100 -- Special case for bindings which bind unlifted variables
101 -- We need to do a case right away, rather than building
102 -- a tuple and doing selections.
103 -- Silently ignore INLINE and SPECIALISE pragmas...
104 ds_val_bind (is_rec, hsbinds) body
105   | [L _ (AbsBinds [] [] exports binds)] <- bagToList hsbinds,
106     or [isUnLiftedType (idType g) | (_, g, _, _) <- exports]
107   = ASSERT (case is_rec of {NonRecursive -> True; other -> False})
108         -- Unlifted bindings are always non-recursive
109         -- and are always a Fun or Pat monobind
110         --
111         -- ToDo: in some bizarre case it's conceivable that there
112         --       could be dict binds in the 'binds'.  (See the notes
113         --       below.  Then pattern-match would fail.  Urk.)
114     let
115       body_w_exports                  = foldr bind_export body exports
116       bind_export (tvs, g, l, _) body = ASSERT( null tvs )
117                                         bindNonRec g (Var l) body
118
119       mk_error_app pat = mkErrorAppDs iRREFUT_PAT_ERROR_ID
120                                     (exprType body)
121                                     (showSDoc (ppr pat))
122     in
123     case bagToList binds of
124       [L loc (FunBind (L _ fun) _ matches _)]
125         -> putSrcSpanDs loc                                     $
126            matchWrapper (FunRhs (idName fun)) matches           `thenDs` \ (args, rhs) ->
127            ASSERT( null args )  -- Functions aren't lifted
128            returnDs (bindNonRec fun rhs body_w_exports)
129
130       [L loc (PatBind pat grhss ty _)]
131         -> putSrcSpanDs loc                     $
132            dsGuarded grhss ty                   `thenDs` \ rhs ->
133            mk_error_app pat                     `thenDs` \ error_expr ->
134            matchSimply rhs PatBindRhs pat body_w_exports error_expr
135
136       other -> pprPanic "dsLet: unlifted" (pprLHsBinds hsbinds $$ ppr body)
137
138 -- Ordinary case for bindings
139 ds_val_bind (is_rec, binds) body
140   = dsLHsBinds binds    `thenDs` \ prs ->
141     returnDs (Let (Rec prs) body)
142         -- Use a Rec regardless of is_rec. 
143         -- Why? Because it allows the binds to be all
144         -- mixed up, which is what happens in one rare case
145         -- Namely, for an AbsBind with no tyvars and no dicts,
146         --         but which does have dictionary bindings.
147         -- See notes with TcSimplify.inferLoop [NO TYVARS]
148         -- It turned out that wrapping a Rec here was the easiest solution
149         --
150         -- NB The previous case dealt with unlifted bindings, so we
151         --    only have to deal with lifted ones now; so Rec is ok
152 \end{code}      
153
154 %************************************************************************
155 %*                                                                      *
156 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
157 %*                                                                      *
158 %************************************************************************
159
160 \begin{code}
161 dsLExpr :: LHsExpr Id -> DsM CoreExpr
162 dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e
163
164 dsExpr :: HsExpr Id -> DsM CoreExpr
165
166 dsExpr (HsPar e)              = dsLExpr e
167 dsExpr (ExprWithTySigOut e _) = dsLExpr e
168 dsExpr (HsVar var)            = returnDs (Var var)
169 dsExpr (HsIPVar ip)           = returnDs (Var (ipNameName ip))
170 dsExpr (HsLit lit)            = dsLit lit
171 dsExpr (HsOverLit lit)        = dsOverLit lit
172
173 dsExpr (NegApp expr neg_expr) 
174   = do  { core_expr <- dsLExpr expr
175         ; core_neg  <- dsExpr neg_expr
176         ; return (core_neg `App` core_expr) }
177
178 dsExpr expr@(HsLam a_Match)
179   = matchWrapper LambdaExpr a_Match     `thenDs` \ (binders, matching_code) ->
180     returnDs (mkLams binders matching_code)
181
182 dsExpr expr@(HsApp fun arg)      
183   = dsLExpr fun         `thenDs` \ core_fun ->
184     dsLExpr arg         `thenDs` \ core_arg ->
185     returnDs (core_fun `App` core_arg)
186 \end{code}
187
188 Operator sections.  At first it looks as if we can convert
189 \begin{verbatim}
190         (expr op)
191 \end{verbatim}
192 to
193 \begin{verbatim}
194         \x -> op expr x
195 \end{verbatim}
196
197 But no!  expr might be a redex, and we can lose laziness badly this
198 way.  Consider
199 \begin{verbatim}
200         map (expr op) xs
201 \end{verbatim}
202 for example.  So we convert instead to
203 \begin{verbatim}
204         let y = expr in \x -> op y x
205 \end{verbatim}
206 If \tr{expr} is actually just a variable, say, then the simplifier
207 will sort it out.
208
209 \begin{code}
210 dsExpr (OpApp e1 op _ e2)
211   = dsLExpr op                                          `thenDs` \ core_op ->
212     -- for the type of y, we need the type of op's 2nd argument
213     dsLExpr e1                          `thenDs` \ x_core ->
214     dsLExpr e2                          `thenDs` \ y_core ->
215     returnDs (mkApps core_op [x_core, y_core])
216     
217 dsExpr (SectionL expr op)
218   = dsLExpr op                                          `thenDs` \ core_op ->
219     -- for the type of y, we need the type of op's 2nd argument
220     let
221         (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
222         -- Must look through an implicit-parameter type; 
223         -- newtype impossible; hence Type.splitFunTys
224     in
225     dsLExpr expr                                `thenDs` \ x_core ->
226     newSysLocalDs x_ty                  `thenDs` \ x_id ->
227     newSysLocalDs y_ty                  `thenDs` \ y_id ->
228
229     returnDs (bindNonRec x_id x_core $
230               Lam y_id (mkApps core_op [Var x_id, Var y_id]))
231
232 -- dsLExpr (SectionR op expr)   -- \ x -> op x expr
233 dsExpr (SectionR op expr)
234   = dsLExpr op                  `thenDs` \ core_op ->
235     -- for the type of x, we need the type of op's 2nd argument
236     let
237         (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
238         -- See comment with SectionL
239     in
240     dsLExpr expr                                `thenDs` \ y_core ->
241     newSysLocalDs x_ty                  `thenDs` \ x_id ->
242     newSysLocalDs y_ty                  `thenDs` \ y_id ->
243
244     returnDs (bindNonRec y_id y_core $
245               Lam x_id (mkApps core_op [Var x_id, Var y_id]))
246
247 dsExpr (HsSCC cc expr)
248   = dsLExpr expr                        `thenDs` \ core_expr ->
249     getModuleDs                 `thenDs` \ mod_name ->
250     returnDs (Note (SCC (mkUserCC cc mod_name)) core_expr)
251
252
253 -- hdaume: core annotation
254
255 dsExpr (HsCoreAnn fs expr)
256   = dsLExpr expr        `thenDs` \ core_expr ->
257     returnDs (Note (CoreNote $ unpackFS fs) core_expr)
258
259 -- Special case to handle unboxed tuple patterns; they can't appear nested
260 dsExpr (HsCase discrim matches@(MatchGroup _ ty))
261  | isUnboxedTupleType (funArgTy ty)
262  =  dsLExpr discrim                     `thenDs` \ core_discrim ->
263     matchWrapper CaseAlt matches        `thenDs` \ ([discrim_var], matching_code) ->
264     case matching_code of
265         Case (Var x) bndr ty alts | x == discrim_var -> 
266                 returnDs (Case core_discrim bndr ty alts)
267         _ -> panic ("dsLExpr: tuple pattern:\n" ++ showSDoc (ppr matching_code))
268
269 dsExpr (HsCase discrim matches)
270   = dsLExpr discrim                     `thenDs` \ core_discrim ->
271     matchWrapper CaseAlt matches        `thenDs` \ ([discrim_var], matching_code) ->
272     returnDs (bindNonRec discrim_var core_discrim matching_code)
273
274 dsExpr (HsLet binds body)
275   = dsLExpr body                `thenDs` \ body' ->
276     dsLocalBinds binds body'
277
278 -- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
279 -- because the interpretation of `stmts' depends on what sort of thing it is.
280 --
281 dsExpr (HsDo ListComp stmts body result_ty)
282   =     -- Special case for list comprehensions
283     dsListComp stmts body elt_ty
284   where
285     [elt_ty] = tcTyConAppArgs result_ty
286
287 dsExpr (HsDo DoExpr stmts body result_ty)
288   = dsDo stmts body result_ty
289
290 dsExpr (HsDo (MDoExpr tbl) stmts body result_ty)
291   = dsMDo tbl stmts body result_ty
292
293 dsExpr (HsDo PArrComp stmts body result_ty)
294   =     -- Special case for array comprehensions
295     dsPArrComp (map unLoc stmts) body elt_ty
296   where
297     [elt_ty] = tcTyConAppArgs result_ty
298
299 dsExpr (HsIf guard_expr then_expr else_expr)
300   = dsLExpr guard_expr  `thenDs` \ core_guard ->
301     dsLExpr then_expr   `thenDs` \ core_then ->
302     dsLExpr 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   = dsLExpr expr `thenDs` \ core_expr ->
313     returnDs (mkLams tyvars core_expr)
314
315 dsExpr (TyApp expr tys)
316   = dsLExpr 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) = dsLExpr 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   = mappM dsLExpr expr_list       `thenDs` \ core_exprs  ->
350     returnDs (mkConApp (tupleCon boxity (length expr_list))
351                        (map (Type .  exprType) core_exprs ++ core_exprs))
352
353 dsExpr (ArithSeq expr (From from))
354   = dsExpr expr           `thenDs` \ expr2 ->
355     dsLExpr from          `thenDs` \ from2 ->
356     returnDs (App expr2 from2)
357
358 dsExpr (ArithSeq expr (FromTo from two))
359   = dsExpr expr           `thenDs` \ expr2 ->
360     dsLExpr from          `thenDs` \ from2 ->
361     dsLExpr two           `thenDs` \ two2 ->
362     returnDs (mkApps expr2 [from2, two2])
363
364 dsExpr (ArithSeq expr (FromThen from thn))
365   = dsExpr expr           `thenDs` \ expr2 ->
366     dsLExpr from          `thenDs` \ from2 ->
367     dsLExpr thn           `thenDs` \ thn2 ->
368     returnDs (mkApps expr2 [from2, thn2])
369
370 dsExpr (ArithSeq expr (FromThenTo from thn two))
371   = dsExpr expr           `thenDs` \ expr2 ->
372     dsLExpr from          `thenDs` \ from2 ->
373     dsLExpr thn           `thenDs` \ thn2 ->
374     dsLExpr two           `thenDs` \ two2 ->
375     returnDs (mkApps expr2 [from2, thn2, two2])
376
377 dsExpr (PArrSeq expr (FromTo from two))
378   = dsExpr expr           `thenDs` \ expr2 ->
379     dsLExpr from          `thenDs` \ from2 ->
380     dsLExpr two           `thenDs` \ two2 ->
381     returnDs (mkApps expr2 [from2, two2])
382
383 dsExpr (PArrSeq expr (FromThenTo from thn two))
384   = dsExpr expr           `thenDs` \ expr2 ->
385     dsLExpr from          `thenDs` \ from2 ->
386     dsLExpr thn           `thenDs` \ thn2 ->
387     dsLExpr two           `thenDs` \ two2 ->
388     returnDs (mkApps expr2 [from2, thn2, two2])
389
390 dsExpr (PArrSeq 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 (RecordCon (L _ data_con_id) 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)    -- Selector id has the field label as its name
426           = case [rhs | (L _ sel_id, rhs) <- rbinds, lbl == idName sel_id] of
427               (rhs:rhss) -> ASSERT( null rhss )
428                             dsLExpr 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 (idDataCon data_con_id)
433         -- The data_con_id is guaranteed to be the wrapper id of the constructor
434     in
435
436     (if null labels
437         then mappM unlabelled_bottom arg_tys
438         else mappM 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 (RecordUpd record_expr [] record_in_ty record_out_ty)
467   = dsLExpr record_expr
468
469 dsExpr expr@(RecordUpd record_expr rbinds record_in_ty record_out_ty)
470   = dsLExpr 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         in_out_ty    = mkFunTy record_in_ty record_out_ty
479
480         mk_val_arg field old_arg_id 
481           = case [rhs | (L _ sel_id, rhs) <- rbinds, field == idName sel_id] of
482               (rhs:rest) -> ASSERT(null rest) rhs
483               []         -> nlHsVar 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                 -- but existentials don't have record types anyway
489             let 
490                 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
491                                         (dataConFieldLabels con) arg_ids
492                 rhs = foldl (\a b -> nlHsApp a b)
493                         (noLoc $ TyApp (nlHsVar (dataConWrapId con)) 
494                                 out_inst_tys)
495                           val_args
496             in
497             returnDs (mkSimpleMatch [noLoc $ ConPatOut (noLoc con) [] [] emptyLHsBinds 
498                                                        (PrefixCon (map nlVarPat arg_ids)) record_in_ty]
499                                     rhs)
500     in
501         -- Record stuff doesn't work for existentials
502         -- The type checker checks for this, but we need 
503         -- worry only about the constructors that are to be updated
504     ASSERT2( all isVanillaDataCon cons_to_upd, ppr expr )
505
506         -- It's important to generate the match with matchWrapper,
507         -- and the right hand sides with applications of the wrapper Id
508         -- so that everything works when we are doing fancy unboxing on the
509         -- constructor aguments.
510     mappM mk_alt cons_to_upd                            `thenDs` \ alts ->
511     matchWrapper RecUpd (MatchGroup alts in_out_ty)     `thenDs` \ ([discrim_var], matching_code) ->
512
513     returnDs (bindNonRec discrim_var record_expr' matching_code)
514
515   where
516     updated_fields :: [FieldLabel]
517     updated_fields = [ idName sel_id | (L _ sel_id,_) <- rbinds]
518
519         -- Get the type constructor from the record_in_ty
520         -- so that we are sure it'll have all its DataCons
521         -- (In GHCI, it's possible that some TyCons may not have all
522         --  their constructors, in a module-loop situation.)
523     tycon       = tcTyConAppTyCon record_in_ty
524     data_cons   = tyConDataCons tycon
525     cons_to_upd = filter has_all_fields data_cons
526
527     has_all_fields :: DataCon -> Bool
528     has_all_fields con_id 
529       = all (`elem` con_fields) updated_fields
530       where
531         con_fields = dataConFieldLabels con_id
532 \end{code}
533
534
535 \noindent
536 \underline{\bf Dictionary lambda and application}
537 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
538 @DictLam@ and @DictApp@ turn into the regular old things.
539 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
540 complicated; reminiscent of fully-applied constructors.
541 \begin{code}
542 dsExpr (DictLam dictvars expr)
543   = dsLExpr expr `thenDs` \ core_expr ->
544     returnDs (mkLams dictvars core_expr)
545
546 ------------------
547
548 dsExpr (DictApp expr dicts)     -- becomes a curried application
549   = dsLExpr expr                        `thenDs` \ core_expr ->
550     returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
551 \end{code}
552
553 Here is where we desugar the Template Haskell brackets and escapes
554
555 \begin{code}
556 -- Template Haskell stuff
557
558 #ifdef GHCI     /* Only if bootstrapping */
559 dsExpr (HsBracketOut x ps) = dsBracket x ps
560 dsExpr (HsSpliceE s)       = pprPanic "dsExpr:splice" (ppr s)
561 #endif
562
563 -- Arrow notation extension
564 dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
565 \end{code}
566
567
568 \begin{code}
569
570 #ifdef DEBUG
571 -- HsSyn constructs that just shouldn't be here:
572 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
573 #endif
574
575 \end{code}
576
577 %--------------------------------------------------------------------
578
579 Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
580 handled in DsListComp).  Basically does the translation given in the
581 Haskell 98 report:
582
583 \begin{code}
584 dsDo    :: [LStmt Id]
585         -> LHsExpr Id
586         -> Type                 -- Type of the whole expression
587         -> DsM CoreExpr
588
589 dsDo stmts body result_ty
590   = go (map unLoc stmts)
591   where
592     go [] = dsLExpr body
593     
594     go (ExprStmt rhs then_expr _ : stmts)
595       = do { rhs2 <- dsLExpr rhs
596            ; then_expr2 <- dsExpr then_expr
597            ; rest <- go stmts
598            ; returnDs (mkApps then_expr2 [rhs2, rest]) }
599     
600     go (LetStmt binds : stmts)
601       = do { rest <- go stmts
602            ; dsLocalBinds binds rest }
603         
604     go (BindStmt pat rhs bind_op fail_op : stmts)
605       = do { body  <- go stmts
606            ; var   <- selectSimpleMatchVarL pat
607            ; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat
608                                   result_ty (cantFailMatchResult body)
609            ; match_code <- handle_failure pat match fail_op
610            ; rhs'       <- dsLExpr rhs
611            ; bind_op'   <- dsExpr bind_op
612            ; returnDs (mkApps bind_op' [rhs', Lam var match_code]) }
613     
614     -- In a do expression, pattern-match failure just calls
615     -- the monadic 'fail' rather than throwing an exception
616     handle_failure pat match fail_op
617       | matchCanFail match
618       = do { fail_op' <- dsExpr fail_op
619            ; fail_msg <- mkStringExpr (mk_fail_msg pat)
620            ; extractMatchResult match (App fail_op' fail_msg) }
621       | otherwise
622       = extractMatchResult match (error "It can't fail") 
623
624 mk_fail_msg pat = "Pattern match failure in do expression at " ++ 
625                   showSDoc (ppr (getLoc pat))
626 \end{code}
627
628 Translation for RecStmt's: 
629 -----------------------------
630 We turn (RecStmt [v1,..vn] stmts) into:
631   
632   (v1,..,vn) <- mfix (\~(v1,..vn). do stmts
633                                       return (v1,..vn))
634
635 \begin{code}
636 dsMDo   :: PostTcTable
637         -> [LStmt Id]
638         -> LHsExpr Id
639         -> Type                 -- Type of the whole expression
640         -> DsM CoreExpr
641
642 dsMDo tbl stmts body result_ty
643   = go (map unLoc stmts)
644   where
645     (m_ty, b_ty) = tcSplitAppTy result_ty       -- result_ty must be of the form (m b)
646     mfix_id   = lookupEvidence tbl mfixName
647     return_id = lookupEvidence tbl returnMName
648     bind_id   = lookupEvidence tbl bindMName
649     then_id   = lookupEvidence tbl thenMName
650     fail_id   = lookupEvidence tbl failMName
651     ctxt      = MDoExpr tbl
652
653     go [] = dsLExpr body
654     
655     go (LetStmt binds : stmts)
656       = do { rest <- go stmts
657            ; dsLocalBinds binds rest }
658
659     go (ExprStmt rhs _ rhs_ty : stmts)
660       = do { rhs2 <- dsLExpr rhs
661            ; rest <- go stmts
662            ; returnDs (mkApps (Var then_id) [Type rhs_ty, Type b_ty, rhs2, rest]) }
663     
664     go (BindStmt pat rhs _ _ : stmts)
665       = do { body  <- go stmts
666            ; var   <- selectSimpleMatchVarL pat
667            ; match <- matchSinglePat (Var var) (StmtCtxt ctxt) pat
668                                   result_ty (cantFailMatchResult body)
669            ; fail_msg   <- mkStringExpr (mk_fail_msg pat)
670            ; let fail_expr = mkApps (Var fail_id) [Type b_ty, fail_msg]
671            ; match_code <- extractMatchResult match fail_expr
672
673            ; rhs'       <- dsLExpr rhs
674            ; returnDs (mkApps (Var bind_id) [Type (hsPatType pat), Type b_ty, 
675                                              rhs', Lam var match_code]) }
676     
677     go (RecStmt rec_stmts later_ids rec_ids rec_rets binds : stmts)
678       = ASSERT( length rec_ids > 0 )
679         ASSERT( length rec_ids == length rec_rets )
680         go (new_bind_stmt : let_stmt : stmts)
681       where
682         new_bind_stmt = mkBindStmt (mk_tup_pat later_pats) mfix_app
683         let_stmt = LetStmt (HsValBinds (ValBindsOut [(Recursive, binds)]))
684
685         
686                 -- Remove the later_ids that appear (without fancy coercions) 
687                 -- in rec_rets, because there's no need to knot-tie them separately
688                 -- See Note [RecStmt] in HsExpr
689         later_ids'   = filter (`notElem` mono_rec_ids) later_ids
690         mono_rec_ids = [ id | HsVar id <- rec_rets ]
691     
692         mfix_app = nlHsApp (noLoc $ TyApp (nlHsVar mfix_id) [tup_ty]) mfix_arg
693         mfix_arg = noLoc $ HsLam (MatchGroup [mkSimpleMatch [mfix_pat] body]
694                                              (mkFunTy tup_ty body_ty))
695
696         -- The rec_tup_pat must bind the rec_ids only; remember that the 
697         --      trimmed_laters may share the same Names
698         -- Meanwhile, the later_pats must bind the later_vars
699         rec_tup_pats = map mk_wild_pat later_ids' ++ map nlVarPat rec_ids
700         later_pats   = map nlVarPat    later_ids' ++ map mk_later_pat rec_ids
701         rets         = map nlHsVar     later_ids' ++ map noLoc rec_rets
702
703         mfix_pat = noLoc $ LazyPat $ mk_tup_pat rec_tup_pats
704         body     = noLoc $ HsDo ctxt rec_stmts return_app body_ty
705         body_ty = mkAppTy m_ty tup_ty
706         tup_ty  = mkCoreTupTy (map idType (later_ids' ++ rec_ids))
707                   -- mkCoreTupTy deals with singleton case
708
709         return_app  = nlHsApp (noLoc $ TyApp (nlHsVar return_id) [tup_ty]) 
710                               (mk_ret_tup rets)
711
712         mk_wild_pat :: Id -> LPat Id 
713         mk_wild_pat v = noLoc $ WildPat $ idType v
714
715         mk_later_pat :: Id -> LPat Id
716         mk_later_pat v | v `elem` later_ids' = mk_wild_pat v
717                        | otherwise           = nlVarPat v
718
719         mk_tup_pat :: [LPat Id] -> LPat Id
720         mk_tup_pat [p] = p
721         mk_tup_pat ps  = noLoc $ TuplePat ps Boxed
722
723         mk_ret_tup :: [LHsExpr Id] -> LHsExpr Id
724         mk_ret_tup [r] = r
725         mk_ret_tup rs  = noLoc $ ExplicitTuple rs Boxed
726 \end{code}