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