79303efa86ca3f5fe29bf643a9b5cf176175216f
[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 import Match            ( matchWrapper, matchSimply, matchSinglePat )
12 import MatchLit         ( dsLit, dsOverLit )
13 import DsBinds          ( dsLHsBinds, dsCoercion )
14 import DsGRHSs          ( dsGuarded )
15 import DsListComp       ( dsListComp, dsPArrComp )
16 import DsUtils          ( mkErrorAppDs, mkStringExpr, mkConsExpr, mkNilExpr,
17                           extractMatchResult, cantFailMatchResult, matchCanFail,
18                           mkCoreTupTy, selectSimpleMatchVarL, lookupEvidence )
19 import DsArrows         ( dsProcExpr )
20 import DsMonad
21
22 #ifdef GHCI
23         -- Template Haskell stuff iff bootstrapped
24 import DsMeta           ( dsBracket )
25 #endif
26
27 import HsSyn
28 import TcHsSyn          ( hsPatType, mkVanillaTuplePat )
29
30 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
31 --     needs to see source types (newtypes etc), and sometimes not
32 --     So WATCH OUT; check each use of split*Ty functions.
33 -- Sigh.  This is a pain.
34
35 import TcType           ( tcSplitAppTy, tcSplitFunTys, tcTyConAppTyCon, 
36                           tcTyConAppArgs, isUnLiftedType, Type, mkAppTy )
37 import Type             ( funArgTy, splitFunTys, isUnboxedTupleType, mkFunTy )
38 import CoreSyn
39 import CoreUtils        ( exprType, mkIfThenElse, bindNonRec )
40
41 import CostCentre       ( mkUserCC )
42 import Id               ( Id, idType, idName, idDataCon )
43 import PrelInfo         ( rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID )
44 import DataCon          ( DataCon, dataConWrapId, dataConFieldLabels, dataConInstOrigArgTys )
45 import DataCon          ( isVanillaDataCon )
46 import TyCon            ( FieldLabel, tyConDataCons )
47 import TysWiredIn       ( tupleCon )
48 import BasicTypes       ( RecFlag(..), Boxity(..), ipNameName )
49 import PrelNames        ( toPName,
50                           returnMName, bindMName, thenMName, failMName,
51                           mfixName )
52 import SrcLoc           ( Located(..), unLoc, getLoc, noLoc )
53 import Util             ( zipEqual, zipWithEqual )
54 import Bag              ( bagToList )
55 import Outputable
56 import FastString
57 \end{code}
58
59
60 %************************************************************************
61 %*                                                                      *
62                 dsLocalBinds, dsValBinds
63 %*                                                                      *
64 %************************************************************************
65
66 \begin{code}
67 dsLocalBinds :: HsLocalBinds Id -> CoreExpr -> DsM CoreExpr
68 dsLocalBinds EmptyLocalBinds    body = return body
69 dsLocalBinds (HsValBinds binds) body = dsValBinds binds body
70 dsLocalBinds (HsIPBinds binds)  body = dsIPBinds  binds body
71
72 -------------------------
73 dsValBinds :: HsValBinds Id -> CoreExpr -> DsM CoreExpr
74 dsValBinds (ValBindsOut binds _) body = foldrDs ds_val_bind body binds
75
76 -------------------------
77 dsIPBinds (IPBinds ip_binds dict_binds) body
78   = do  { prs <- dsLHsBinds dict_binds
79         ; let inner = foldr (\(x,r) e -> Let (NonRec x r) e) body prs 
80         ; foldrDs ds_ip_bind inner ip_binds }
81   where
82     ds_ip_bind (L _ (IPBind n e)) body
83       = dsLExpr e       `thenDs` \ e' ->
84         returnDs (Let (NonRec (ipNameName n) e') body)
85
86 -------------------------
87 ds_val_bind :: (RecFlag, LHsBinds Id) -> CoreExpr -> DsM CoreExpr
88 -- Special case for bindings which bind unlifted variables
89 -- We need to do a case right away, rather than building
90 -- a tuple and doing selections.
91 -- Silently ignore INLINE and SPECIALISE pragmas...
92 ds_val_bind (NonRecursive, hsbinds) body
93   | [L _ (AbsBinds [] [] exports binds)] <- bagToList hsbinds,
94     (L loc bind : null_binds) <- bagToList binds,
95     or [isUnLiftedType (idType g) | (_, g, _, _) <- exports]
96     || isBangHsBind bind
97   = let
98       body_w_exports                  = foldr bind_export body exports
99       bind_export (tvs, g, l, _) body = ASSERT( null tvs )
100                                         bindNonRec g (Var l) body
101     in
102     ASSERT (null null_binds)
103         -- Non-recursive, non-overloaded bindings only come in ones
104         -- ToDo: in some bizarre case it's conceivable that there
105         --       could be dict binds in the 'binds'.  (See the notes
106         --       below.  Then pattern-match would fail.  Urk.)
107     putSrcSpanDs loc    $
108     case bind of
109       FunBind { fun_id = L _ fun, fun_matches = matches, fun_co_fn = co_fn }
110         -> matchWrapper (FunRhs (idName fun)) matches           `thenDs` \ (args, rhs) ->
111            ASSERT( null args )  -- Functions aren't lifted
112            ASSERT( isIdCoercion co_fn )
113            returnDs (bindNonRec fun rhs body_w_exports)
114
115       PatBind {pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty }
116         -> putSrcSpanDs loc                     $
117            dsGuarded grhss ty                   `thenDs` \ rhs ->
118            mk_error_app pat                     `thenDs` \ error_expr ->
119            matchSimply rhs PatBindRhs pat body_w_exports error_expr
120
121       other -> pprPanic "dsLet: unlifted" (pprLHsBinds hsbinds $$ ppr body)
122   where
123       mk_error_app pat = mkErrorAppDs iRREFUT_PAT_ERROR_ID
124                                     (exprType body)
125                                     (showSDoc (ppr pat))
126
127 -- Ordinary case for bindings; none should be unlifted
128 ds_val_bind (is_rec, binds) body
129   = do  { prs <- dsLHsBinds binds
130         ; ASSERT( not (any (isUnLiftedType . idType . fst) prs) )
131           case prs of
132             []    -> return body
133             other -> return (Let (Rec prs) body) }
134         -- Use a Rec regardless of is_rec. 
135         -- Why? Because it allows the binds to be all
136         -- mixed up, which is what happens in one rare case
137         -- Namely, for an AbsBind with no tyvars and no dicts,
138         --         but which does have dictionary bindings.
139         -- See notes with TcSimplify.inferLoop [NO TYVARS]
140         -- It turned out that wrapping a Rec here was the easiest solution
141         --
142         -- NB The previous case dealt with unlifted bindings, so we
143         --    only have to deal with lifted ones now; so Rec is ok
144 \end{code}      
145
146 %************************************************************************
147 %*                                                                      *
148 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
149 %*                                                                      *
150 %************************************************************************
151
152 \begin{code}
153 dsLExpr :: LHsExpr Id -> DsM CoreExpr
154 dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e
155
156 dsExpr :: HsExpr Id -> DsM CoreExpr
157
158 dsExpr (HsPar e)              = dsLExpr e
159 dsExpr (ExprWithTySigOut e _) = dsLExpr e
160 dsExpr (HsVar var)            = returnDs (Var var)
161 dsExpr (HsIPVar ip)           = returnDs (Var (ipNameName ip))
162 dsExpr (HsLit lit)            = dsLit lit
163 dsExpr (HsOverLit lit)        = dsOverLit lit
164
165 dsExpr (NegApp expr neg_expr) 
166   = do  { core_expr <- dsLExpr expr
167         ; core_neg  <- dsExpr neg_expr
168         ; return (core_neg `App` core_expr) }
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   = dsLExpr fun         `thenDs` \ core_fun ->
176     dsLExpr 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   = dsLExpr op                                          `thenDs` \ core_op ->
204     -- for the type of y, we need the type of op's 2nd argument
205     dsLExpr e1                          `thenDs` \ x_core ->
206     dsLExpr e2                          `thenDs` \ y_core ->
207     returnDs (mkApps core_op [x_core, y_core])
208     
209 dsExpr (SectionL expr op)
210   = dsLExpr 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     dsLExpr 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 -- dsLExpr (SectionR op expr)   -- \ x -> op x expr
225 dsExpr (SectionR op expr)
226   = dsLExpr 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     dsLExpr 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 (HsSCC cc expr)
240   = dsLExpr 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   = dsLExpr expr        `thenDs` \ core_expr ->
249     returnDs (Note (CoreNote $ unpackFS fs) core_expr)
250
251 -- Special case to handle unboxed tuple patterns; they can't appear nested
252 -- The idea is that 
253 --      case e of (# p1, p2 #) -> rhs
254 -- should desugar to
255 --      case e of (# x1, x2 #) -> ... match p1, p2 ...
256 -- NOT
257 --      let x = e in case x of ....
258 --
259 -- But there may be a big 
260 --      let fail = ... in case e of ...
261 -- wrapping the whole case, which complicates matters slightly
262 -- It all seems a bit fragile.  Test is dsrun013.
263
264 dsExpr (HsCase discrim matches@(MatchGroup _ ty))
265  | isUnboxedTupleType (funArgTy ty)
266  =  dsLExpr discrim                     `thenDs` \ core_discrim ->
267     matchWrapper CaseAlt matches        `thenDs` \ ([discrim_var], matching_code) ->
268     let
269         scrungle (Case (Var x) bndr ty alts) 
270                 | x == discrim_var = Case core_discrim bndr ty alts
271         scrungle (Let binds body)  = Let binds (scrungle body)
272         scrungle other = panic ("dsLExpr: tuple pattern:\n" ++ showSDoc (ppr other))
273     in
274     returnDs (scrungle matching_code)
275
276 dsExpr (HsCase discrim matches)
277   = dsLExpr discrim                     `thenDs` \ core_discrim ->
278     matchWrapper CaseAlt matches        `thenDs` \ ([discrim_var], matching_code) ->
279     returnDs (bindNonRec discrim_var core_discrim matching_code)
280
281 dsExpr (HsLet binds body)
282   = dsLExpr body                `thenDs` \ body' ->
283     dsLocalBinds binds body'
284
285 -- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
286 -- because the interpretation of `stmts' depends on what sort of thing it is.
287 --
288 dsExpr (HsDo ListComp stmts body result_ty)
289   =     -- Special case for list comprehensions
290     dsListComp stmts body elt_ty
291   where
292     [elt_ty] = tcTyConAppArgs result_ty
293
294 dsExpr (HsDo DoExpr stmts body result_ty)
295   = dsDo stmts body result_ty
296
297 dsExpr (HsDo (MDoExpr tbl) stmts body result_ty)
298   = dsMDo tbl stmts body result_ty
299
300 dsExpr (HsDo PArrComp stmts body result_ty)
301   =     -- Special case for array comprehensions
302     dsPArrComp (map unLoc stmts) body elt_ty
303   where
304     [elt_ty] = tcTyConAppArgs result_ty
305
306 dsExpr (HsIf guard_expr then_expr else_expr)
307   = dsLExpr guard_expr  `thenDs` \ core_guard ->
308     dsLExpr then_expr   `thenDs` \ core_then ->
309     dsLExpr else_expr   `thenDs` \ core_else ->
310     returnDs (mkIfThenElse core_guard core_then core_else)
311 \end{code}
312
313
314 \noindent
315 \underline{\bf Type lambda and application}
316 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~
317 \begin{code}
318 dsExpr (TyLam tyvars expr)
319   = dsLExpr expr `thenDs` \ core_expr ->
320     returnDs (mkLams tyvars core_expr)
321
322 dsExpr (TyApp expr tys)
323   = dsLExpr expr                `thenDs` \ core_expr ->
324     returnDs (mkTyApps core_expr tys)
325 \end{code}
326
327
328 \noindent
329 \underline{\bf Various data construction things}
330 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
331 \begin{code}
332 dsExpr (ExplicitList ty xs)
333   = go xs
334   where
335     go []     = returnDs (mkNilExpr ty)
336     go (x:xs) = dsLExpr x                               `thenDs` \ core_x ->
337                 go xs                                   `thenDs` \ core_xs ->
338                 returnDs (mkConsExpr ty core_x core_xs)
339
340 -- we create a list from the array elements and convert them into a list using
341 -- `PrelPArr.toP'
342 --
343 --  * the main disadvantage to this scheme is that `toP' traverses the list
344 --   twice: once to determine the length and a second time to put to elements
345 --   into the array; this inefficiency could be avoided by exposing some of
346 --   the innards of `PrelPArr' to the compiler (ie, have a `PrelPArrBase') so
347 --   that we can exploit the fact that we already know the length of the array
348 --   here at compile time
349 --
350 dsExpr (ExplicitPArr ty xs)
351   = dsLookupGlobalId toPName                            `thenDs` \toP      ->
352     dsExpr (ExplicitList ty xs)                         `thenDs` \coreList ->
353     returnDs (mkApps (Var toP) [Type ty, coreList])
354
355 dsExpr (ExplicitTuple expr_list boxity)
356   = mappM dsLExpr expr_list       `thenDs` \ core_exprs  ->
357     returnDs (mkConApp (tupleCon boxity (length expr_list))
358                        (map (Type .  exprType) core_exprs ++ core_exprs))
359
360 dsExpr (ArithSeq expr (From from))
361   = dsExpr expr           `thenDs` \ expr2 ->
362     dsLExpr from          `thenDs` \ from2 ->
363     returnDs (App expr2 from2)
364
365 dsExpr (ArithSeq expr (FromTo from two))
366   = dsExpr expr           `thenDs` \ expr2 ->
367     dsLExpr from          `thenDs` \ from2 ->
368     dsLExpr two           `thenDs` \ two2 ->
369     returnDs (mkApps expr2 [from2, two2])
370
371 dsExpr (ArithSeq expr (FromThen from thn))
372   = dsExpr expr           `thenDs` \ expr2 ->
373     dsLExpr from          `thenDs` \ from2 ->
374     dsLExpr thn           `thenDs` \ thn2 ->
375     returnDs (mkApps expr2 [from2, thn2])
376
377 dsExpr (ArithSeq expr (FromThenTo from thn two))
378   = dsExpr expr           `thenDs` \ expr2 ->
379     dsLExpr from          `thenDs` \ from2 ->
380     dsLExpr thn           `thenDs` \ thn2 ->
381     dsLExpr two           `thenDs` \ two2 ->
382     returnDs (mkApps expr2 [from2, thn2, two2])
383
384 dsExpr (PArrSeq expr (FromTo from two))
385   = dsExpr expr           `thenDs` \ expr2 ->
386     dsLExpr from          `thenDs` \ from2 ->
387     dsLExpr two           `thenDs` \ two2 ->
388     returnDs (mkApps expr2 [from2, two2])
389
390 dsExpr (PArrSeq expr (FromThenTo from thn two))
391   = dsExpr expr           `thenDs` \ expr2 ->
392     dsLExpr from          `thenDs` \ from2 ->
393     dsLExpr thn           `thenDs` \ thn2 ->
394     dsLExpr two           `thenDs` \ two2 ->
395     returnDs (mkApps expr2 [from2, thn2, two2])
396
397 dsExpr (PArrSeq expr _)
398   = panic "DsExpr.dsExpr: Infinite parallel array!"
399     -- the parser shouldn't have generated it and the renamer and typechecker
400     -- shouldn't have let it through
401 \end{code}
402
403 \noindent
404 \underline{\bf Record construction and update}
405 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
406 For record construction we do this (assuming T has three arguments)
407 \begin{verbatim}
408         T { op2 = e }
409 ==>
410         let err = /\a -> recConErr a 
411         T (recConErr t1 "M.lhs/230/op1") 
412           e 
413           (recConErr t1 "M.lhs/230/op3")
414 \end{verbatim}
415 @recConErr@ then converts its arugment string into a proper message
416 before printing it as
417 \begin{verbatim}
418         M.lhs, line 230: missing field op1 was evaluated
419 \end{verbatim}
420
421 We also handle @C{}@ as valid construction syntax for an unlabelled
422 constructor @C@, setting all of @C@'s fields to bottom.
423
424 \begin{code}
425 dsExpr (RecordCon (L _ data_con_id) con_expr rbinds)
426   = dsExpr con_expr     `thenDs` \ con_expr' ->
427     let
428         (arg_tys, _) = tcSplitFunTys (exprType con_expr')
429         -- A newtype in the corner should be opaque; 
430         -- hence TcType.tcSplitFunTys
431
432         mk_arg (arg_ty, lbl)    -- Selector id has the field label as its name
433           = case [rhs | (L _ sel_id, rhs) <- rbinds, lbl == idName sel_id] of
434               (rhs:rhss) -> ASSERT( null rhss )
435                             dsLExpr rhs
436               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showSDoc (ppr lbl))
437         unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty ""
438
439         labels = dataConFieldLabels (idDataCon data_con_id)
440         -- The data_con_id is guaranteed to be the wrapper id of the constructor
441     in
442
443     (if null labels
444         then mappM unlabelled_bottom arg_tys
445         else mappM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels))
446         `thenDs` \ con_args ->
447
448     returnDs (mkApps con_expr' con_args)
449 \end{code}
450
451 Record update is a little harder. Suppose we have the decl:
452 \begin{verbatim}
453         data T = T1 {op1, op2, op3 :: Int}
454                | T2 {op4, op2 :: Int}
455                | T3
456 \end{verbatim}
457 Then we translate as follows:
458 \begin{verbatim}
459         r { op2 = e }
460 ===>
461         let op2 = e in
462         case r of
463           T1 op1 _ op3 -> T1 op1 op2 op3
464           T2 op4 _     -> T2 op4 op2
465           other        -> recUpdError "M.lhs/230"
466 \end{verbatim}
467 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
468 RHSs, and do not generate a Core constructor application directly, because the constructor
469 might do some argument-evaluation first; and may have to throw away some
470 dictionaries.
471
472 \begin{code}
473 dsExpr (RecordUpd record_expr [] record_in_ty record_out_ty)
474   = dsLExpr record_expr
475
476 dsExpr expr@(RecordUpd record_expr rbinds record_in_ty record_out_ty)
477   = dsLExpr record_expr         `thenDs` \ record_expr' ->
478
479         -- Desugar the rbinds, and generate let-bindings if
480         -- necessary so that we don't lose sharing
481
482     let
483         in_inst_tys  = tcTyConAppArgs record_in_ty      -- Newtype opaque
484         out_inst_tys = tcTyConAppArgs record_out_ty     -- Newtype opaque
485         in_out_ty    = mkFunTy record_in_ty record_out_ty
486
487         mk_val_arg field old_arg_id 
488           = case [rhs | (L _ sel_id, rhs) <- rbinds, field == idName sel_id] of
489               (rhs:rest) -> ASSERT(null rest) rhs
490               []         -> nlHsVar old_arg_id
491
492         mk_alt con
493           = newSysLocalsDs (dataConInstOrigArgTys con in_inst_tys) `thenDs` \ arg_ids ->
494                 -- This call to dataConInstOrigArgTys won't work for existentials
495                 -- but existentials don't have record types anyway
496             let 
497                 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
498                                         (dataConFieldLabels con) arg_ids
499                 rhs = foldl (\a b -> nlHsApp a b)
500                         (noLoc $ TyApp (nlHsVar (dataConWrapId con)) 
501                                 out_inst_tys)
502                           val_args
503             in
504             returnDs (mkSimpleMatch [noLoc $ ConPatOut (noLoc con) [] [] emptyLHsBinds 
505                                                        (PrefixCon (map nlVarPat arg_ids)) record_in_ty]
506                                     rhs)
507     in
508         -- Record stuff doesn't work for existentials
509         -- The type checker checks for this, but we need 
510         -- worry only about the constructors that are to be updated
511     ASSERT2( all isVanillaDataCon cons_to_upd, ppr expr )
512
513         -- It's important to generate the match with matchWrapper,
514         -- and the right hand sides with applications of the wrapper Id
515         -- so that everything works when we are doing fancy unboxing on the
516         -- constructor aguments.
517     mappM mk_alt cons_to_upd                            `thenDs` \ alts ->
518     matchWrapper RecUpd (MatchGroup alts in_out_ty)     `thenDs` \ ([discrim_var], matching_code) ->
519
520     returnDs (bindNonRec discrim_var record_expr' matching_code)
521
522   where
523     updated_fields :: [FieldLabel]
524     updated_fields = [ idName sel_id | (L _ sel_id,_) <- rbinds]
525
526         -- Get the type constructor from the record_in_ty
527         -- so that we are sure it'll have all its DataCons
528         -- (In GHCI, it's possible that some TyCons may not have all
529         --  their constructors, in a module-loop situation.)
530     tycon       = tcTyConAppTyCon record_in_ty
531     data_cons   = tyConDataCons tycon
532     cons_to_upd = filter has_all_fields data_cons
533
534     has_all_fields :: DataCon -> Bool
535     has_all_fields con_id 
536       = all (`elem` con_fields) updated_fields
537       where
538         con_fields = dataConFieldLabels con_id
539 \end{code}
540
541
542 \noindent
543 \underline{\bf Dictionary lambda and application}
544 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
545 @DictLam@ and @DictApp@ turn into the regular old things.
546 (OLD:) @DictFunApp@ also becomes a curried application, albeit slightly more
547 complicated; reminiscent of fully-applied constructors.
548 \begin{code}
549 dsExpr (DictLam dictvars expr)
550   = dsLExpr expr `thenDs` \ core_expr ->
551     returnDs (mkLams dictvars core_expr)
552
553 ------------------
554
555 dsExpr (DictApp expr dicts)     -- becomes a curried application
556   = dsLExpr expr                        `thenDs` \ core_expr ->
557     returnDs (foldl (\f d -> f `App` (Var d)) core_expr dicts)
558
559 dsExpr (HsCoerce co_fn e) = dsCoercion co_fn (dsExpr e)
560 \end{code}
561
562 Here is where we desugar the Template Haskell brackets and escapes
563
564 \begin{code}
565 -- Template Haskell stuff
566
567 #ifdef GHCI     /* Only if bootstrapping */
568 dsExpr (HsBracketOut x ps) = dsBracket x ps
569 dsExpr (HsSpliceE s)       = pprPanic "dsExpr:splice" (ppr s)
570 #endif
571
572 -- Arrow notation extension
573 dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
574 \end{code}
575
576
577 \begin{code}
578
579 #ifdef DEBUG
580 -- HsSyn constructs that just shouldn't be here:
581 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
582 #endif
583
584 \end{code}
585
586 %--------------------------------------------------------------------
587
588 Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
589 handled in DsListComp).  Basically does the translation given in the
590 Haskell 98 report:
591
592 \begin{code}
593 dsDo    :: [LStmt Id]
594         -> LHsExpr Id
595         -> Type                 -- Type of the whole expression
596         -> DsM CoreExpr
597
598 dsDo stmts body result_ty
599   = go (map unLoc stmts)
600   where
601     go [] = dsLExpr body
602     
603     go (ExprStmt rhs then_expr _ : stmts)
604       = do { rhs2 <- dsLExpr rhs
605            ; then_expr2 <- dsExpr then_expr
606            ; rest <- go stmts
607            ; returnDs (mkApps then_expr2 [rhs2, rest]) }
608     
609     go (LetStmt binds : stmts)
610       = do { rest <- go stmts
611            ; dsLocalBinds binds rest }
612         
613     go (BindStmt pat rhs bind_op fail_op : stmts)
614       = do { body  <- go stmts
615            ; var   <- selectSimpleMatchVarL pat
616            ; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat
617                                   result_ty (cantFailMatchResult body)
618            ; match_code <- handle_failure pat match fail_op
619            ; rhs'       <- dsLExpr rhs
620            ; bind_op'   <- dsExpr bind_op
621            ; returnDs (mkApps bind_op' [rhs', Lam var match_code]) }
622     
623     -- In a do expression, pattern-match failure just calls
624     -- the monadic 'fail' rather than throwing an exception
625     handle_failure pat match fail_op
626       | matchCanFail match
627       = do { fail_op' <- dsExpr fail_op
628            ; fail_msg <- mkStringExpr (mk_fail_msg pat)
629            ; extractMatchResult match (App fail_op' fail_msg) }
630       | otherwise
631       = extractMatchResult match (error "It can't fail") 
632
633 mk_fail_msg pat = "Pattern match failure in do expression at " ++ 
634                   showSDoc (ppr (getLoc pat))
635 \end{code}
636
637 Translation for RecStmt's: 
638 -----------------------------
639 We turn (RecStmt [v1,..vn] stmts) into:
640   
641   (v1,..,vn) <- mfix (\~(v1,..vn). do stmts
642                                       return (v1,..vn))
643
644 \begin{code}
645 dsMDo   :: PostTcTable
646         -> [LStmt Id]
647         -> LHsExpr Id
648         -> Type                 -- Type of the whole expression
649         -> DsM CoreExpr
650
651 dsMDo tbl stmts body result_ty
652   = go (map unLoc stmts)
653   where
654     (m_ty, b_ty) = tcSplitAppTy result_ty       -- result_ty must be of the form (m b)
655     mfix_id   = lookupEvidence tbl mfixName
656     return_id = lookupEvidence tbl returnMName
657     bind_id   = lookupEvidence tbl bindMName
658     then_id   = lookupEvidence tbl thenMName
659     fail_id   = lookupEvidence tbl failMName
660     ctxt      = MDoExpr tbl
661
662     go [] = dsLExpr body
663     
664     go (LetStmt binds : stmts)
665       = do { rest <- go stmts
666            ; dsLocalBinds binds rest }
667
668     go (ExprStmt rhs _ rhs_ty : stmts)
669       = do { rhs2 <- dsLExpr rhs
670            ; rest <- go stmts
671            ; returnDs (mkApps (Var then_id) [Type rhs_ty, Type b_ty, rhs2, rest]) }
672     
673     go (BindStmt pat rhs _ _ : stmts)
674       = do { body  <- go stmts
675            ; var   <- selectSimpleMatchVarL pat
676            ; match <- matchSinglePat (Var var) (StmtCtxt ctxt) pat
677                                   result_ty (cantFailMatchResult body)
678            ; fail_msg   <- mkStringExpr (mk_fail_msg pat)
679            ; let fail_expr = mkApps (Var fail_id) [Type b_ty, fail_msg]
680            ; match_code <- extractMatchResult match fail_expr
681
682            ; rhs'       <- dsLExpr rhs
683            ; returnDs (mkApps (Var bind_id) [Type (hsPatType pat), Type b_ty, 
684                                              rhs', Lam var match_code]) }
685     
686     go (RecStmt rec_stmts later_ids rec_ids rec_rets binds : stmts)
687       = ASSERT( length rec_ids > 0 )
688         ASSERT( length rec_ids == length rec_rets )
689         go (new_bind_stmt : let_stmt : stmts)
690       where
691         new_bind_stmt = mkBindStmt (mk_tup_pat later_pats) mfix_app
692         let_stmt = LetStmt (HsValBinds (ValBindsOut [(Recursive, binds)] []))
693
694         
695                 -- Remove the later_ids that appear (without fancy coercions) 
696                 -- in rec_rets, because there's no need to knot-tie them separately
697                 -- See Note [RecStmt] in HsExpr
698         later_ids'   = filter (`notElem` mono_rec_ids) later_ids
699         mono_rec_ids = [ id | HsVar id <- rec_rets ]
700     
701         mfix_app = nlHsApp (noLoc $ TyApp (nlHsVar mfix_id) [tup_ty]) mfix_arg
702         mfix_arg = noLoc $ HsLam (MatchGroup [mkSimpleMatch [mfix_pat] body]
703                                              (mkFunTy tup_ty body_ty))
704
705         -- The rec_tup_pat must bind the rec_ids only; remember that the 
706         --      trimmed_laters may share the same Names
707         -- Meanwhile, the later_pats must bind the later_vars
708         rec_tup_pats = map mk_wild_pat later_ids' ++ map nlVarPat rec_ids
709         later_pats   = map nlVarPat    later_ids' ++ map mk_later_pat rec_ids
710         rets         = map nlHsVar     later_ids' ++ map noLoc rec_rets
711
712         mfix_pat = noLoc $ LazyPat $ mk_tup_pat rec_tup_pats
713         body     = noLoc $ HsDo ctxt rec_stmts return_app body_ty
714         body_ty = mkAppTy m_ty tup_ty
715         tup_ty  = mkCoreTupTy (map idType (later_ids' ++ rec_ids))
716                   -- mkCoreTupTy deals with singleton case
717
718         return_app  = nlHsApp (noLoc $ TyApp (nlHsVar return_id) [tup_ty]) 
719                               (mk_ret_tup rets)
720
721         mk_wild_pat :: Id -> LPat Id 
722         mk_wild_pat v = noLoc $ WildPat $ idType v
723
724         mk_later_pat :: Id -> LPat Id
725         mk_later_pat v | v `elem` later_ids' = mk_wild_pat v
726                        | otherwise           = nlVarPat v
727
728         mk_tup_pat :: [LPat Id] -> LPat Id
729         mk_tup_pat [p] = p
730         mk_tup_pat ps  = noLoc $ mkVanillaTuplePat ps Boxed
731
732         mk_ret_tup :: [LHsExpr Id] -> LHsExpr Id
733         mk_ret_tup [r] = r
734         mk_ret_tup rs  = noLoc $ ExplicitTuple rs Boxed
735 \end{code}