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