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