put coqPassCoreToCore on the CoreM monad, greatly simplify Desugar.lhs
[ghc-hetmet.git] / compiler / deSugar / DsExpr.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Desugaring exporessions.
7
8 \begin{code}
9 {-# OPTIONS -fno-warn-incomplete-patterns #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 -- for details
15
16 module DsExpr ( dsExpr, dsLExpr, dsLocalBinds, dsValBinds, dsLit ) where
17
18 #include "HsVersions.h"
19
20 import Match
21 import MatchLit
22 import DsBinds
23 import DsGRHSs
24 import DsListComp
25 import DsUtils
26 import DsArrows
27 import DsMonad
28 import Name
29 import NameEnv
30
31 #ifdef GHCI
32         -- Template Haskell stuff iff bootstrapped
33 import DsMeta
34 #endif
35
36 import HsSyn
37
38 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
39 --     needs to see source types
40 import TcType
41 import Type
42 import Coercion
43 import CoreSyn
44 import CoreUtils
45 import CoreFVs
46 import MkCore
47
48 import DynFlags
49 import StaticFlags
50 import CostCentre
51 import Id
52 import VarSet
53 import VarEnv
54 import DataCon
55 import TysWiredIn
56 import BasicTypes
57 import PrelNames
58 import Maybes
59 import SrcLoc
60 import Util
61 import Bag
62 import Outputable
63 import FastString
64
65 import Control.Monad
66 \end{code}
67
68
69 %************************************************************************
70 %*                                                                      *
71                 dsLocalBinds, dsValBinds
72 %*                                                                      *
73 %************************************************************************
74
75 \begin{code}
76 dsLocalBinds :: HsLocalBinds Id -> CoreExpr -> DsM CoreExpr
77 dsLocalBinds EmptyLocalBinds    body = return body
78 dsLocalBinds (HsValBinds binds) body = dsValBinds binds body
79 dsLocalBinds (HsIPBinds binds)  body = dsIPBinds  binds body
80
81 -------------------------
82 dsValBinds :: HsValBinds Id -> CoreExpr -> DsM CoreExpr
83 dsValBinds (ValBindsOut binds _) body = foldrM ds_val_bind body binds
84
85 -------------------------
86 dsIPBinds :: HsIPBinds Id -> CoreExpr -> DsM CoreExpr
87 dsIPBinds (IPBinds ip_binds ev_binds) body
88   = do  { ds_ev_binds <- dsTcEvBinds ev_binds
89         ; let inner = wrapDsEvBinds ds_ev_binds body
90                 -- The dict bindings may not be in 
91                 -- dependency order; hence Rec
92         ; foldrM ds_ip_bind inner ip_binds }
93   where
94     ds_ip_bind (L _ (IPBind n e)) body
95       = do e' <- dsLExpr e
96            return (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 (NonRecursive, hsbinds) body
105   | [L loc bind] <- bagToList hsbinds,
106         -- Non-recursive, non-overloaded bindings only come in ones
107         -- ToDo: in some bizarre case it's conceivable that there
108         --       could be dict binds in the 'binds'.  (See the notes
109         --       below.  Then pattern-match would fail.  Urk.)
110     strictMatchOnly bind
111   = putSrcSpanDs loc (dsStrictBind bind body)
112
113 -- Ordinary case for bindings; none should be unlifted
114 ds_val_bind (_is_rec, binds) body
115   = do  { prs <- dsLHsBinds binds
116         ; ASSERT2( not (any (isUnLiftedType . idType . fst) prs), ppr _is_rec $$ ppr binds )
117           case prs of
118             [] -> return body
119             _  -> return (Let (Rec prs) body) }
120         -- Use a Rec regardless of is_rec. 
121         -- Why? Because it allows the binds to be all
122         -- mixed up, which is what happens in one rare case
123         -- Namely, for an AbsBind with no tyvars and no dicts,
124         --         but which does have dictionary bindings.
125         -- See notes with TcSimplify.inferLoop [NO TYVARS]
126         -- It turned out that wrapping a Rec here was the easiest solution
127         --
128         -- NB The previous case dealt with unlifted bindings, so we
129         --    only have to deal with lifted ones now; so Rec is ok
130
131 ------------------
132 dsStrictBind :: HsBind Id -> CoreExpr -> DsM CoreExpr
133 dsStrictBind (AbsBinds { abs_tvs = [], abs_ev_vars = []
134                , abs_exports = exports
135                , abs_ev_binds = ev_binds
136                , abs_binds = binds }) body
137   = do { ds_ev_binds <- dsTcEvBinds ev_binds
138        ; let body1 = foldr bind_export body exports
139              bind_export (_, g, l, _) b = bindNonRec g (Var l) b
140        ; body2 <- foldlBagM (\body bind -> dsStrictBind (unLoc bind) body) 
141                             body1 binds 
142        ; return (wrapDsEvBinds ds_ev_binds body2) }
143
144 dsStrictBind (FunBind { fun_id = L _ fun, fun_matches = matches, fun_co_fn = co_fn 
145                       , fun_tick = tick, fun_infix = inf }) body
146                 -- Can't be a bang pattern (that looks like a PatBind)
147                 -- so must be simply unboxed
148   = do { (args, rhs) <- matchWrapper (FunRhs (idName fun ) inf) matches
149        ; MASSERT( null args ) -- Functions aren't lifted
150        ; MASSERT( isIdHsWrapper co_fn )
151        ; rhs' <- mkOptTickBox tick rhs
152        ; return (bindNonRec fun rhs' body) }
153
154 dsStrictBind (PatBind {pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty }) body
155   =     -- let C x# y# = rhs in body
156         -- ==> case rhs of C x# y# -> body
157     do { rhs <- dsGuarded grhss ty
158        ; let upat = unLoc pat
159              eqn = EqnInfo { eqn_pats = [upat], 
160                              eqn_rhs = cantFailMatchResult body }
161        ; var    <- selectMatchVar upat
162        ; result <- matchEquations PatBindRhs [var] [eqn] (exprType body)
163        ; return (scrungleMatch var rhs result) }
164
165 dsStrictBind bind body = pprPanic "dsLet: unlifted" (ppr bind $$ ppr body)
166
167 ----------------------
168 strictMatchOnly :: HsBind Id -> Bool
169 strictMatchOnly (AbsBinds { abs_binds = binds })
170   = anyBag (strictMatchOnly . unLoc) binds
171 strictMatchOnly (PatBind { pat_lhs = lpat, pat_rhs_ty = ty })
172   =  isUnboxedTupleType ty 
173   || isBangLPat lpat   
174   || any (isUnLiftedType . idType) (collectPatBinders lpat)
175 strictMatchOnly (FunBind { fun_id = L _ id })
176   = isUnLiftedType (idType id)
177 strictMatchOnly _ = False -- I hope!  Checked immediately by caller in fact
178
179 scrungleMatch :: Id -> CoreExpr -> CoreExpr -> CoreExpr
180 -- Returns something like (let var = scrut in body)
181 -- but if var is an unboxed-tuple type, it inlines it in a fragile way
182 -- Special case to handle unboxed tuple patterns; they can't appear nested
183 -- The idea is that 
184 --      case e of (# p1, p2 #) -> rhs
185 -- should desugar to
186 --      case e of (# x1, x2 #) -> ... match p1, p2 ...
187 -- NOT
188 --      let x = e in case x of ....
189 --
190 -- But there may be a big 
191 --      let fail = ... in case e of ...
192 -- wrapping the whole case, which complicates matters slightly
193 -- It all seems a bit fragile.  Test is dsrun013.
194
195 scrungleMatch var scrut body
196   | isUnboxedTupleType (idType var) = scrungle body
197   | otherwise                       = bindNonRec var scrut body
198   where
199     scrungle (Case (Var x) bndr ty alts)
200                     | x == var = Case scrut bndr ty alts
201     scrungle (Let binds body)  = Let binds (scrungle body)
202     scrungle other = panic ("scrungleMatch: tuple pattern:\n" ++ showSDoc (ppr other))
203
204 \end{code}
205
206 %************************************************************************
207 %*                                                                      *
208 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
209 %*                                                                      *
210 %************************************************************************
211
212 \begin{code}
213 dsLExpr :: LHsExpr Id -> DsM CoreExpr
214
215 dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e
216
217 dsExpr :: HsExpr Id -> DsM CoreExpr
218 dsExpr (HsPar e)              = dsLExpr e
219
220 dsExpr (HsHetMetBrak c   e)   = do { e' <- dsExpr (unLoc e)
221                                  ; brak <- dsLookupGlobalId hetmet_brak_name
222                                  ; return $ mkApps (Var brak) [ (Type c), (Type $ exprType e'), e'] }
223 dsExpr (HsHetMetEsc  c t e)   = do { e' <- dsExpr (unLoc e)
224                                  ; esc <- dsLookupGlobalId hetmet_esc_name
225                                  ; return $ mkApps (Var esc)  [ (Type c), (Type t), e'] }
226 dsExpr (HsHetMetCSP  c   e)   = do { e' <- dsExpr (unLoc e)
227                                  ; csp <- dsLookupGlobalId hetmet_csp_name
228                                  ; return $ mkApps (Var csp)  [ (Type c), (Type $ exprType e'), e'] }
229 dsExpr (ExprWithTySigOut e _) = dsLExpr e
230 dsExpr (HsVar var)            = return (Var var)
231 dsExpr (HsIPVar ip)           = return (Var (ipNameName ip))
232 dsExpr (HsLit lit)            = dsLit lit
233 dsExpr (HsOverLit lit)        = dsOverLit lit
234
235 dsExpr (HsWrap co_fn e)
236   = do { co_fn' <- dsHsWrapper co_fn
237        ; e' <- dsExpr e
238        ; warn_id <- doptDs Opt_WarnIdentities
239        ; when warn_id $ warnAboutIdentities e' co_fn'
240        ; return (co_fn' e') }
241
242 dsExpr (NegApp expr neg_expr) 
243   = App <$> dsExpr neg_expr <*> dsLExpr expr
244
245 dsExpr (HsLam a_Match)
246   = uncurry mkLams <$> matchWrapper LambdaExpr a_Match
247
248 dsExpr (HsApp fun arg)
249   = mkCoreAppDs <$> dsLExpr fun <*>  dsLExpr arg
250 \end{code}
251
252 Operator sections.  At first it looks as if we can convert
253 \begin{verbatim}
254         (expr op)
255 \end{verbatim}
256 to
257 \begin{verbatim}
258         \x -> op expr x
259 \end{verbatim}
260
261 But no!  expr might be a redex, and we can lose laziness badly this
262 way.  Consider
263 \begin{verbatim}
264         map (expr op) xs
265 \end{verbatim}
266 for example.  So we convert instead to
267 \begin{verbatim}
268         let y = expr in \x -> op y x
269 \end{verbatim}
270 If \tr{expr} is actually just a variable, say, then the simplifier
271 will sort it out.
272
273 \begin{code}
274 dsExpr (OpApp e1 op _ e2)
275   = -- for the type of y, we need the type of op's 2nd argument
276     mkCoreAppsDs <$> dsLExpr op <*> mapM dsLExpr [e1, e2]
277     
278 dsExpr (SectionL expr op)       -- Desugar (e !) to ((!) e)
279   = mkCoreAppDs <$> dsLExpr op <*> dsLExpr expr
280
281 -- dsLExpr (SectionR op expr)   -- \ x -> op x expr
282 dsExpr (SectionR op expr) = do
283     core_op <- dsLExpr op
284     -- for the type of x, we need the type of op's 2nd argument
285     let (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
286         -- See comment with SectionL
287     y_core <- dsLExpr expr
288     x_id <- newSysLocalDs x_ty
289     y_id <- newSysLocalDs y_ty
290     return (bindNonRec y_id y_core $
291             Lam x_id (mkCoreAppsDs core_op [Var x_id, Var y_id]))
292
293 dsExpr (ExplicitTuple tup_args boxity)
294   = do { let go (lam_vars, args) (Missing ty)
295                     -- For every missing expression, we need
296                     -- another lambda in the desugaring.
297                = do { lam_var <- newSysLocalDs ty
298                     ; return (lam_var : lam_vars, Var lam_var : args) }
299              go (lam_vars, args) (Present expr)
300                     -- Expressions that are present don't generate
301                     -- lambdas, just arguments.
302                = do { core_expr <- dsLExpr expr
303                     ; return (lam_vars, core_expr : args) }
304
305        ; (lam_vars, args) <- foldM go ([], []) (reverse tup_args)
306                 -- The reverse is because foldM goes left-to-right
307
308        ; return $ mkCoreLams lam_vars $ 
309                   mkConApp (tupleCon boxity (length tup_args))
310                            (map (Type . exprType) args ++ args) }
311
312 dsExpr (HsSCC cc expr) = do
313     mod_name <- getModuleDs
314     Note (SCC (mkUserCC cc mod_name)) <$> dsLExpr expr
315
316 dsExpr (HsCoreAnn fs expr)
317   = Note (CoreNote $ unpackFS fs) <$> dsLExpr expr
318
319 dsExpr (HsCase discrim matches@(MatchGroup _ rhs_ty)) 
320   | isEmptyMatchGroup matches   -- A Core 'case' is always non-empty
321   =                             -- So desugar empty HsCase to error call
322     mkErrorAppDs pAT_ERROR_ID (funResultTy rhs_ty) (ptext (sLit "case"))
323
324   | otherwise
325   = do { core_discrim <- dsLExpr discrim
326        ; ([discrim_var], matching_code) <- matchWrapper CaseAlt matches
327        ; return (scrungleMatch discrim_var core_discrim matching_code) }
328
329 -- Pepe: The binds are in scope in the body but NOT in the binding group
330 --       This is to avoid silliness in breakpoints
331 dsExpr (HsLet binds body) = do
332     body' <- dsLExpr body
333     dsLocalBinds binds body'
334
335 -- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
336 -- because the interpretation of `stmts' depends on what sort of thing it is.
337 --
338 dsExpr (HsDo ListComp  stmts res_ty) = dsListComp stmts res_ty
339 dsExpr (HsDo PArrComp  stmts _)      = dsPArrComp (map unLoc stmts)
340 dsExpr (HsDo DoExpr    stmts _)      = dsDo stmts 
341 dsExpr (HsDo GhciStmt  stmts _)      = dsDo stmts 
342 dsExpr (HsDo MDoExpr   stmts _)      = dsDo stmts 
343 dsExpr (HsDo MonadComp stmts _)      = dsMonadComp stmts
344
345 dsExpr (HsIf mb_fun guard_expr then_expr else_expr)
346   = do { pred <- dsLExpr guard_expr
347        ; b1 <- dsLExpr then_expr
348        ; b2 <- dsLExpr else_expr
349        ; case mb_fun of
350            Just fun -> do { core_fun <- dsExpr fun
351                           ; return (mkCoreApps core_fun [pred,b1,b2]) }
352            Nothing  -> return $ mkIfThenElse pred b1 b2 }
353 \end{code}
354
355
356 \noindent
357 \underline{\bf Various data construction things}
358 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
359 \begin{code}
360 dsExpr (ExplicitList elt_ty xs) 
361   = dsExplicitList elt_ty xs
362
363 -- We desugar [:x1, ..., xn:] as
364 --   singletonP x1 +:+ ... +:+ singletonP xn
365 --
366 dsExpr (ExplicitPArr ty []) = do
367     emptyP <- dsLookupDPHId emptyPName
368     return (Var emptyP `App` Type ty)
369 dsExpr (ExplicitPArr ty xs) = do
370     singletonP <- dsLookupDPHId singletonPName
371     appP       <- dsLookupDPHId appPName
372     xs'        <- mapM dsLExpr xs
373     return . foldr1 (binary appP) $ map (unary singletonP) xs'
374   where
375     unary  fn x   = mkApps (Var fn) [Type ty, x]
376     binary fn x y = mkApps (Var fn) [Type ty, x, y]
377
378 dsExpr (ArithSeq expr (From from))
379   = App <$> dsExpr expr <*> dsLExpr from
380
381 dsExpr (ArithSeq expr (FromTo from to))
382   = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, to]
383
384 dsExpr (ArithSeq expr (FromThen from thn))
385   = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, thn]
386
387 dsExpr (ArithSeq expr (FromThenTo from thn to))
388   = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, thn, to]
389
390 dsExpr (PArrSeq expr (FromTo from to))
391   = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, to]
392
393 dsExpr (PArrSeq expr (FromThenTo from thn to))
394   = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, thn, to]
395
396 dsExpr (PArrSeq _ _)
397   = panic "DsExpr.dsExpr: Infinite parallel array!"
398     -- the parser shouldn't have generated it and the renamer and typechecker
399     -- shouldn't have let it through
400 \end{code}
401
402 \noindent
403 \underline{\bf Record construction and update}
404 %              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
405 For record construction we do this (assuming T has three arguments)
406 \begin{verbatim}
407         T { op2 = e }
408 ==>
409         let err = /\a -> recConErr a 
410         T (recConErr t1 "M.lhs/230/op1") 
411           e 
412           (recConErr t1 "M.lhs/230/op3")
413 \end{verbatim}
414 @recConErr@ then converts its arugment string into a proper message
415 before printing it as
416 \begin{verbatim}
417         M.lhs, line 230: missing field op1 was evaluated
418 \end{verbatim}
419
420 We also handle @C{}@ as valid construction syntax for an unlabelled
421 constructor @C@, setting all of @C@'s fields to bottom.
422
423 \begin{code}
424 dsExpr (RecordCon (L _ data_con_id) con_expr rbinds) = do
425     con_expr' <- dsExpr con_expr
426     let
427         (arg_tys, _) = tcSplitFunTys (exprType con_expr')
428         -- A newtype in the corner should be opaque; 
429         -- hence TcType.tcSplitFunTys
430
431         mk_arg (arg_ty, lbl)    -- Selector id has the field label as its name
432           = case findField (rec_flds rbinds) lbl of
433               (rhs:rhss) -> ASSERT( null rhss )
434                             dsLExpr rhs
435               []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (ppr lbl)
436         unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty empty
437
438         labels = dataConFieldLabels (idDataCon data_con_id)
439         -- The data_con_id is guaranteed to be the wrapper id of the constructor
440     
441     con_args <- if null labels
442                 then mapM unlabelled_bottom arg_tys
443                 else mapM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels)
444     
445     return (mkApps con_expr' con_args)
446 \end{code}
447
448 Record update is a little harder. Suppose we have the decl:
449 \begin{verbatim}
450         data T = T1 {op1, op2, op3 :: Int}
451                | T2 {op4, op2 :: Int}
452                | T3
453 \end{verbatim}
454 Then we translate as follows:
455 \begin{verbatim}
456         r { op2 = e }
457 ===>
458         let op2 = e in
459         case r of
460           T1 op1 _ op3 -> T1 op1 op2 op3
461           T2 op4 _     -> T2 op4 op2
462           other        -> recUpdError "M.lhs/230"
463 \end{verbatim}
464 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
465 RHSs, and do not generate a Core constructor application directly, because the constructor
466 might do some argument-evaluation first; and may have to throw away some
467 dictionaries.
468
469 Note [Update for GADTs]
470 ~~~~~~~~~~~~~~~~~~~~~~~
471 Consider 
472    data T a b where
473      T1 { f1 :: a } :: T a Int
474
475 Then the wrapper function for T1 has type 
476    $WT1 :: a -> T a Int
477 But if x::T a b, then
478    x { f1 = v } :: T a b   (not T a Int!)
479 So we need to cast (T a Int) to (T a b).  Sigh.
480
481 \begin{code}
482 dsExpr expr@(RecordUpd record_expr (HsRecFields { rec_flds = fields })
483                        cons_to_upd in_inst_tys out_inst_tys)
484   | null fields
485   = dsLExpr record_expr
486   | otherwise
487   = ASSERT2( notNull cons_to_upd, ppr expr )
488
489     do  { record_expr' <- dsLExpr record_expr
490         ; field_binds' <- mapM ds_field fields
491         ; let upd_fld_env :: NameEnv Id -- Maps field name to the LocalId of the field binding
492               upd_fld_env = mkNameEnv [(f,l) | (f,l,_) <- field_binds']
493
494         -- It's important to generate the match with matchWrapper,
495         -- and the right hand sides with applications of the wrapper Id
496         -- so that everything works when we are doing fancy unboxing on the
497         -- constructor aguments.
498         ; alts <- mapM (mk_alt upd_fld_env) cons_to_upd
499         ; ([discrim_var], matching_code) 
500                 <- matchWrapper RecUpd (MatchGroup alts in_out_ty)
501
502         ; return (add_field_binds field_binds' $
503                   bindNonRec discrim_var record_expr' matching_code) }
504   where
505     ds_field :: HsRecField Id (LHsExpr Id) -> DsM (Name, Id, CoreExpr)
506       -- Clone the Id in the HsRecField, because its Name is that
507       -- of the record selector, and we must not make that a lcoal binder
508       -- else we shadow other uses of the record selector
509       -- Hence 'lcl_id'.  Cf Trac #2735
510     ds_field rec_field = do { rhs <- dsLExpr (hsRecFieldArg rec_field)
511                             ; let fld_id = unLoc (hsRecFieldId rec_field)
512                             ; lcl_id <- newSysLocalDs (idType fld_id)
513                             ; return (idName fld_id, lcl_id, rhs) }
514
515     add_field_binds [] expr = expr
516     add_field_binds ((_,b,r):bs) expr = bindNonRec b r (add_field_binds bs expr)
517
518         -- Awkwardly, for families, the match goes 
519         -- from instance type to family type
520     tycon     = dataConTyCon (head cons_to_upd)
521     in_ty     = mkTyConApp tycon in_inst_tys
522     in_out_ty = mkFunTy in_ty (mkFamilyTyConApp tycon out_inst_tys)
523
524     mk_alt upd_fld_env con
525       = do { let (univ_tvs, ex_tvs, eq_spec, 
526                   theta, arg_tys, _) = dataConFullSig con
527                  subst = mkTopTvSubst (univ_tvs `zip` in_inst_tys)
528
529                 -- I'm not bothering to clone the ex_tvs
530            ; eqs_vars   <- mapM newPredVarDs (substTheta subst (eqSpecPreds eq_spec))
531            ; theta_vars <- mapM newPredVarDs (substTheta subst theta)
532            ; arg_ids    <- newSysLocalsDs (substTys subst arg_tys)
533            ; let val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
534                                          (dataConFieldLabels con) arg_ids
535                  mk_val_arg field_name pat_arg_id 
536                      = nlHsVar (lookupNameEnv upd_fld_env field_name `orElse` pat_arg_id)
537                  inst_con = noLoc $ HsWrap wrap (HsVar (dataConWrapId con))
538                         -- Reconstruct with the WrapId so that unpacking happens
539                  wrap = mkWpEvVarApps theta_vars          `WpCompose` 
540                         mkWpTyApps    (mkTyVarTys ex_tvs) `WpCompose`
541                         mkWpTyApps [ty | (tv, ty) <- univ_tvs `zip` out_inst_tys
542                                        , not (tv `elemVarEnv` wrap_subst) ]
543                  rhs = foldl (\a b -> nlHsApp a b) inst_con val_args
544
545                         -- Tediously wrap the application in a cast
546                         -- Note [Update for GADTs]
547                  wrapped_rhs | null eq_spec = rhs
548                              | otherwise    = mkLHsWrap (WpCast wrap_co) rhs
549                  wrap_co = mkTyConAppCo tycon [ lookup tv ty
550                                               | (tv,ty) <- univ_tvs `zip` out_inst_tys]
551                  lookup univ_tv ty = case lookupVarEnv wrap_subst univ_tv of
552                                         Just co' -> co'
553                                         Nothing  -> mkReflCo ty
554                  wrap_subst = mkVarEnv [ (tv, mkSymCo (mkCoVarCo co_var))
555                                        | ((tv,_),co_var) <- eq_spec `zip` eqs_vars ]
556
557                  pat = noLoc $ ConPatOut { pat_con = noLoc con, pat_tvs = ex_tvs
558                                          , pat_dicts = eqs_vars ++ theta_vars
559                                          , pat_binds = emptyTcEvBinds
560                                          , pat_args = PrefixCon $ map nlVarPat arg_ids
561                                          , pat_ty = in_ty }
562            ; return (mkSimpleMatch [pat] wrapped_rhs) }
563
564 \end{code}
565
566 Here is where we desugar the Template Haskell brackets and escapes
567
568 \begin{code}
569 -- Template Haskell stuff
570
571 #ifdef GHCI     /* Only if bootstrapping */
572 dsExpr (HsBracketOut x ps) = dsBracket x ps
573 dsExpr (HsSpliceE s)       = pprPanic "dsExpr:splice" (ppr s)
574 #endif
575
576 -- Arrow notation extension
577 dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
578 \end{code}
579
580 Hpc Support 
581
582 \begin{code}
583 dsExpr (HsTick ix vars e) = do
584   e' <- dsLExpr e
585   mkTickBox ix vars e'
586
587 -- There is a problem here. The then and else branches
588 -- have no free variables, so they are open to lifting.
589 -- We need someway of stopping this.
590 -- This will make no difference to binary coverage
591 -- (did you go here: YES or NO), but will effect accurate
592 -- tick counting.
593
594 dsExpr (HsBinTick ixT ixF e) = do
595   e2 <- dsLExpr e
596   do { ASSERT(exprType e2 `eqType` boolTy)
597        mkBinaryTickBox ixT ixF e2
598      }
599 \end{code}
600
601 \begin{code}
602
603 -- HsSyn constructs that just shouldn't be here:
604 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
605
606
607 findField :: [HsRecField Id arg] -> Name -> [arg]
608 findField rbinds lbl 
609   = [rhs | HsRecField { hsRecFieldId = id, hsRecFieldArg = rhs } <- rbinds 
610          , lbl == idName (unLoc id) ]
611 \end{code}
612
613 %--------------------------------------------------------------------
614
615 Note [Desugaring explicit lists]
616 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
617 Explicit lists are desugared in a cleverer way to prevent some
618 fruitless allocations.  Essentially, whenever we see a list literal
619 [x_1, ..., x_n] we:
620
621 1. Find the tail of the list that can be allocated statically (say
622    [x_k, ..., x_n]) by later stages and ensure we desugar that
623    normally: this makes sure that we don't cause a code size increase
624    by having the cons in that expression fused (see later) and hence
625    being unable to statically allocate any more
626
627 2. For the prefix of the list which cannot be allocated statically,
628    say [x_1, ..., x_(k-1)], we turn it into an expression involving
629    build so that if we find any foldrs over it it will fuse away
630    entirely!
631    
632    So in this example we will desugar to:
633    build (\c n -> x_1 `c` x_2 `c` .... `c` foldr c n [x_k, ..., x_n]
634    
635    If fusion fails to occur then build will get inlined and (since we
636    defined a RULE for foldr (:) []) we will get back exactly the
637    normal desugaring for an explicit list.
638
639 This optimisation can be worth a lot: up to 25% of the total
640 allocation in some nofib programs. Specifically
641
642         Program           Size    Allocs   Runtime  CompTime
643         rewrite          +0.0%    -26.3%      0.02     -1.8%
644            ansi          -0.3%    -13.8%      0.00     +0.0%
645            lift          +0.0%     -8.7%      0.00     -2.3%
646
647 Of course, if rules aren't turned on then there is pretty much no
648 point doing this fancy stuff, and it may even be harmful.
649
650 =======>  Note by SLPJ Dec 08.
651
652 I'm unconvinced that we should *ever* generate a build for an explicit
653 list.  See the comments in GHC.Base about the foldr/cons rule, which 
654 points out that (foldr k z [a,b,c]) may generate *much* less code than
655 (a `k` b `k` c `k` z).
656
657 Furthermore generating builds messes up the LHS of RULES. 
658 Example: the foldr/single rule in GHC.Base
659    foldr k z [x] = ...
660 We do not want to generate a build invocation on the LHS of this RULE!
661
662 We fix this by disabling rules in rule LHSs, and testing that
663 flag here; see Note [Desugaring RULE left hand sides] in Desugar
664
665 To test this I've added a (static) flag -fsimple-list-literals, which
666 makes all list literals be generated via the simple route.  
667
668
669 \begin{code}
670 dsExplicitList :: PostTcType -> [LHsExpr Id] -> DsM CoreExpr
671 -- See Note [Desugaring explicit lists]
672 dsExplicitList elt_ty xs
673   = do { dflags <- getDOptsDs
674        ; xs' <- mapM dsLExpr xs
675        ; let (dynamic_prefix, static_suffix) = spanTail is_static xs'
676        ; if opt_SimpleListLiterals                      -- -fsimple-list-literals
677          || not (dopt Opt_EnableRewriteRules dflags)    -- Rewrite rules off
678                 -- Don't generate a build if there are no rules to eliminate it!
679                 -- See Note [Desugaring RULE left hand sides] in Desugar
680          || null dynamic_prefix   -- Avoid build (\c n. foldr c n xs)!
681          then return $ mkListExpr elt_ty xs'
682          else mkBuildExpr elt_ty (mkSplitExplicitList dynamic_prefix static_suffix) }
683   where
684     is_static :: CoreExpr -> Bool
685     is_static e = all is_static_var (varSetElems (exprFreeVars e))
686
687     is_static_var :: Var -> Bool
688     is_static_var v 
689       | isId v = isExternalName (idName v)  -- Top-level things are given external names
690       | otherwise = False                   -- Type variables
691
692     mkSplitExplicitList prefix suffix (c, _) (n, n_ty)
693       = do { let suffix' = mkListExpr elt_ty suffix
694            ; folded_suffix <- mkFoldrExpr elt_ty n_ty (Var c) (Var n) suffix'
695            ; return (foldr (App . App (Var c)) folded_suffix prefix) }
696
697 spanTail :: (a -> Bool) -> [a] -> ([a], [a])
698 spanTail f xs = (reverse rejected, reverse satisfying)
699     where (satisfying, rejected) = span f $ reverse xs
700 \end{code}
701
702 Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
703 handled in DsListComp).  Basically does the translation given in the
704 Haskell 98 report:
705
706 \begin{code}
707 dsDo :: [LStmt Id] -> DsM CoreExpr
708 dsDo stmts
709   = goL stmts
710   where
711     goL [] = panic "dsDo"
712     goL (L loc stmt:lstmts) = putSrcSpanDs loc (go loc stmt lstmts)
713   
714     go _ (LastStmt body _) stmts
715       = ASSERT( null stmts ) dsLExpr body
716         -- The 'return' op isn't used for 'do' expressions
717
718     go _ (ExprStmt rhs then_expr _ _) stmts
719       = do { rhs2 <- dsLExpr rhs
720            ; warnDiscardedDoBindings rhs (exprType rhs2) 
721            ; then_expr2 <- dsExpr then_expr
722            ; rest <- goL stmts
723            ; return (mkApps then_expr2 [rhs2, rest]) }
724     
725     go _ (LetStmt binds) stmts
726       = do { rest <- goL stmts
727            ; dsLocalBinds binds rest }
728
729     go _ (BindStmt pat rhs bind_op fail_op) stmts
730       = do  { body     <- goL stmts
731             ; rhs'     <- dsLExpr rhs
732             ; bind_op' <- dsExpr bind_op
733             ; var   <- selectSimpleMatchVarL pat
734             ; let bind_ty = exprType bind_op'   -- rhs -> (pat -> res1) -> res2
735                   res1_ty = funResultTy (funArgTy (funResultTy bind_ty))
736             ; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat
737                                       res1_ty (cantFailMatchResult body)
738             ; match_code <- handle_failure pat match fail_op
739             ; return (mkApps bind_op' [rhs', Lam var match_code]) }
740     
741     go loc (RecStmt { recS_stmts = rec_stmts, recS_later_ids = later_ids
742                     , recS_rec_ids = rec_ids, recS_ret_fn = return_op
743                     , recS_mfix_fn = mfix_op, recS_bind_fn = bind_op
744                     , recS_rec_rets = rec_rets, recS_ret_ty = body_ty }) stmts
745       = ASSERT( length rec_ids > 0 )
746         goL (new_bind_stmt : stmts)
747       where
748         new_bind_stmt = L loc $ BindStmt (mkLHsPatTup later_pats)
749                                          mfix_app bind_op 
750                                          noSyntaxExpr  -- Tuple cannot fail
751
752         tup_ids      = rec_ids ++ filterOut (`elem` rec_ids) later_ids
753         tup_ty       = mkBoxedTupleTy (map idType tup_ids) -- Deals with singleton case
754         rec_tup_pats = map nlVarPat tup_ids
755         later_pats   = rec_tup_pats
756         rets         = map noLoc rec_rets
757         mfix_app     = nlHsApp (noLoc mfix_op) mfix_arg
758         mfix_arg     = noLoc $ HsLam (MatchGroup [mkSimpleMatch [mfix_pat] body]
759                                                  (mkFunTy tup_ty body_ty))
760         mfix_pat     = noLoc $ LazyPat $ mkLHsPatTup rec_tup_pats
761         body         = noLoc $ HsDo DoExpr (rec_stmts ++ [ret_stmt]) body_ty
762         ret_app      = nlHsApp (noLoc return_op) (mkLHsTupleExpr rets)
763         ret_stmt     = noLoc $ mkLastStmt ret_app
764                      -- This LastStmt will be desugared with dsDo, 
765                      -- which ignores the return_op in the LastStmt,
766                      -- so we must apply the return_op explicitly 
767
768 handle_failure :: LPat Id -> MatchResult -> SyntaxExpr Id -> DsM CoreExpr
769     -- In a do expression, pattern-match failure just calls
770     -- the monadic 'fail' rather than throwing an exception
771 handle_failure pat match fail_op
772   | matchCanFail match
773   = do { fail_op' <- dsExpr fail_op
774        ; fail_msg <- mkStringExpr (mk_fail_msg pat)
775        ; extractMatchResult match (App fail_op' fail_msg) }
776   | otherwise
777   = extractMatchResult match (error "It can't fail")
778
779 mk_fail_msg :: Located e -> String
780 mk_fail_msg pat = "Pattern match failure in do expression at " ++ 
781                   showSDoc (ppr (getLoc pat))
782 \end{code}
783
784
785 %************************************************************************
786 %*                                                                      *
787                  Warning about identities
788 %*                                                                      *
789 %************************************************************************
790
791 Warn about functions that convert between one type and another
792 when the to- and from- types are the same.  Then it's probably
793 (albeit not definitely) the identity
794 \begin{code}
795 warnAboutIdentities :: CoreExpr -> (CoreExpr -> CoreExpr) -> DsM ()
796 warnAboutIdentities (Var v) co_fn
797   | idName v `elem` conversionNames
798   , let fun_ty = exprType (co_fn (Var v))
799   , Just (arg_ty, res_ty) <- splitFunTy_maybe fun_ty
800   , arg_ty `eqType` res_ty  -- So we are converting  ty -> ty
801   = warnDs (vcat [ ptext (sLit "Call of") <+> ppr v <+> dcolon <+> ppr fun_ty
802                  , nest 2 $ ptext (sLit "can probably be omitted")
803                  , parens (ptext (sLit "Use -fno-warn-identities to suppress this messsage)"))
804            ])
805 warnAboutIdentities _ _ = return ()
806
807 conversionNames :: [Name]
808 conversionNames
809   = [ toIntegerName, toRationalName
810     , fromIntegralName, realToFracName ]
811  -- We can't easily add fromIntegerName, fromRationalName,
812  -- becuase they are generated by literals
813 \end{code}
814
815 %************************************************************************
816 %*                                                                      *
817 \subsection{Errors and contexts}
818 %*                                                                      *
819 %************************************************************************
820
821 \begin{code}
822 -- Warn about certain types of values discarded in monadic bindings (#3263)
823 warnDiscardedDoBindings :: LHsExpr Id -> Type -> DsM ()
824 warnDiscardedDoBindings rhs rhs_ty
825   | Just (m_ty, elt_ty) <- tcSplitAppTy_maybe rhs_ty
826   = do {  -- Warn about discarding non-() things in 'monadic' binding
827        ; warn_unused <- doptDs Opt_WarnUnusedDoBind
828        ; if warn_unused && not (isUnitTy elt_ty)
829          then warnDs (unusedMonadBind rhs elt_ty)
830          else 
831          -- Warn about discarding m a things in 'monadic' binding of the same type,
832          -- but only if we didn't already warn due to Opt_WarnUnusedDoBind
833     do { warn_wrong <- doptDs Opt_WarnWrongDoBind
834        ; case tcSplitAppTy_maybe elt_ty of
835            Just (elt_m_ty, _) | warn_wrong, m_ty `eqType` elt_m_ty
836                               -> warnDs (wrongMonadBind rhs elt_ty)
837            _ -> return () } }
838
839   | otherwise   -- RHS does have type of form (m ty), which is wierd
840   = return ()   -- but at lesat this warning is irrelevant
841
842 unusedMonadBind :: LHsExpr Id -> Type -> SDoc
843 unusedMonadBind rhs elt_ty
844   = ptext (sLit "A do-notation statement discarded a result of type") <+> ppr elt_ty <> dot $$
845     ptext (sLit "Suppress this warning by saying \"_ <- ") <> ppr rhs <> ptext (sLit "\",") $$
846     ptext (sLit "or by using the flag -fno-warn-unused-do-bind")
847
848 wrongMonadBind :: LHsExpr Id -> Type -> SDoc
849 wrongMonadBind rhs elt_ty
850   = ptext (sLit "A do-notation statement discarded a result of type") <+> ppr elt_ty <> dot $$
851     ptext (sLit "Suppress this warning by saying \"_ <- ") <> ppr rhs <> ptext (sLit "\",") $$
852     ptext (sLit "or by using the flag -fno-warn-wrong-do-bind")
853 \end{code}