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