Major patch to add -fwarn-redundant-constraints
[ghc.git] / compiler / deSugar / DsExpr.hs
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
9 {-# LANGUAGE CPP #-}
10
11 module DsExpr ( dsExpr, dsLExpr, dsLocalBinds, dsValBinds, dsLit ) where
12
13 #include "HsVersions.h"
14
15 import Match
16 import MatchLit
17 import DsBinds
18 import DsGRHSs
19 import DsListComp
20 import DsUtils
21 import DsArrows
22 import DsMonad
23 import Name
24 import NameEnv
25 import FamInstEnv( topNormaliseType )
26
27 #ifdef GHCI
28 -- Template Haskell stuff iff bootstrapped
29 import DsMeta
30 #endif
31
32 import HsSyn
33
34 import Platform
35 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
36 -- needs to see source types
37 import TcType
38 import Coercion ( Role(..) )
39 import TcEvidence
40 import TcRnMonad
41 import Type
42 import CoreSyn
43 import CoreUtils
44 import CoreFVs
45 import MkCore
46
47 import DynFlags
48 import CostCentre
49 import Id
50 import Module
51 import VarSet
52 import VarEnv
53 import ConLike
54 import DataCon
55 import TysWiredIn
56 import PrelNames
57 import BasicTypes
58 import Maybes
59 import SrcLoc
60 import Util
61 import Bag
62 import Outputable
63 import FastString
64
65 import IdInfo
66 import Data.IORef ( atomicModifyIORef, modifyIORef )
67
68 import Control.Monad
69 import GHC.Fingerprint
70
71 {-
72 ************************************************************************
73 * *
74 dsLocalBinds, dsValBinds
75 * *
76 ************************************************************************
77 -}
78
79 dsLocalBinds :: HsLocalBinds Id -> CoreExpr -> DsM CoreExpr
80 dsLocalBinds EmptyLocalBinds body = return body
81 dsLocalBinds (HsValBinds binds) body = dsValBinds binds body
82 dsLocalBinds (HsIPBinds binds) body = dsIPBinds binds body
83
84 -------------------------
85 dsValBinds :: HsValBinds Id -> CoreExpr -> DsM CoreExpr
86 dsValBinds (ValBindsOut binds _) body = foldrM ds_val_bind body binds
87 dsValBinds (ValBindsIn _ _) _ = panic "dsValBinds ValBindsIn"
88
89 -------------------------
90 dsIPBinds :: HsIPBinds Id -> CoreExpr -> DsM CoreExpr
91 dsIPBinds (IPBinds ip_binds ev_binds) body
92 = do { ds_binds <- dsTcEvBinds ev_binds
93 ; let inner = mkCoreLets ds_binds body
94 -- The dict bindings may not be in
95 -- dependency order; hence Rec
96 ; foldrM ds_ip_bind inner ip_binds }
97 where
98 ds_ip_bind (L _ (IPBind ~(Right n) e)) body
99 = do e' <- dsLExpr e
100 return (Let (NonRec n e') body)
101
102 -------------------------
103 ds_val_bind :: (RecFlag, LHsBinds Id) -> CoreExpr -> DsM CoreExpr
104 -- Special case for bindings which bind unlifted variables
105 -- We need to do a case right away, rather than building
106 -- a tuple and doing selections.
107 -- Silently ignore INLINE and SPECIALISE pragmas...
108 ds_val_bind (NonRecursive, hsbinds) body
109 | [L loc bind] <- bagToList hsbinds,
110 -- Non-recursive, non-overloaded bindings only come in ones
111 -- ToDo: in some bizarre case it's conceivable that there
112 -- could be dict binds in the 'binds'. (See the notes
113 -- below. Then pattern-match would fail. Urk.)
114 strictMatchOnly bind
115 = putSrcSpanDs loc (dsStrictBind bind body)
116
117 -- Ordinary case for bindings; none should be unlifted
118 ds_val_bind (_is_rec, binds) body
119 = do { prs <- dsLHsBinds binds
120 ; ASSERT2( not (any (isUnLiftedType . idType . fst) prs), ppr _is_rec $$ ppr binds )
121 case prs of
122 [] -> return body
123 _ -> return (Let (Rec prs) body) }
124 -- Use a Rec regardless of is_rec.
125 -- Why? Because it allows the binds to be all
126 -- mixed up, which is what happens in one rare case
127 -- Namely, for an AbsBind with no tyvars and no dicts,
128 -- but which does have dictionary bindings.
129 -- See notes with TcSimplify.inferLoop [NO TYVARS]
130 -- It turned out that wrapping a Rec here was the easiest solution
131 --
132 -- NB The previous case dealt with unlifted bindings, so we
133 -- only have to deal with lifted ones now; so Rec is ok
134
135 ------------------
136 dsStrictBind :: HsBind Id -> CoreExpr -> DsM CoreExpr
137 dsStrictBind (AbsBinds { abs_tvs = [], abs_ev_vars = []
138 , abs_exports = exports
139 , abs_ev_binds = ev_binds
140 , abs_binds = lbinds }) body
141 = do { let body1 = foldr bind_export body exports
142 bind_export export b = bindNonRec (abe_poly export) (Var (abe_mono export)) b
143 ; body2 <- foldlBagM (\body lbind -> dsStrictBind (unLoc lbind) body)
144 body1 lbinds
145 ; ds_binds <- dsTcEvBinds_s ev_binds
146 ; return (mkCoreLets ds_binds body2) }
147
148 dsStrictBind (FunBind { fun_id = L _ fun, fun_matches = matches, fun_co_fn = co_fn
149 , fun_tick = tick, fun_infix = inf }) body
150 -- Can't be a bang pattern (that looks like a PatBind)
151 -- so must be simply unboxed
152 = do { (args, rhs) <- matchWrapper (FunRhs (idName fun ) inf) matches
153 ; MASSERT( null args ) -- Functions aren't lifted
154 ; MASSERT( isIdHsWrapper co_fn )
155 ; let rhs' = mkOptTickBox tick rhs
156 ; return (bindNonRec fun rhs' body) }
157
158 dsStrictBind (PatBind {pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty }) body
159 = -- let C x# y# = rhs in body
160 -- ==> case rhs of C x# y# -> body
161 do { rhs <- dsGuarded grhss ty
162 ; let upat = unLoc pat
163 eqn = EqnInfo { eqn_pats = [upat],
164 eqn_rhs = cantFailMatchResult body }
165 ; var <- selectMatchVar upat
166 ; result <- matchEquations PatBindRhs [var] [eqn] (exprType body)
167 ; return (bindNonRec var rhs result) }
168
169 dsStrictBind bind body = pprPanic "dsLet: unlifted" (ppr bind $$ ppr body)
170
171 ----------------------
172 strictMatchOnly :: HsBind Id -> Bool
173 strictMatchOnly (AbsBinds { abs_binds = lbinds })
174 = anyBag (strictMatchOnly . unLoc) lbinds
175 strictMatchOnly (PatBind { pat_lhs = lpat, pat_rhs_ty = rhs_ty })
176 = isUnLiftedType rhs_ty
177 || isStrictLPat lpat
178 || any (isUnLiftedType . idType) (collectPatBinders lpat)
179 strictMatchOnly (FunBind { fun_id = L _ id })
180 = isUnLiftedType (idType id)
181 strictMatchOnly _ = False -- I hope! Checked immediately by caller in fact
182
183 {-
184 ************************************************************************
185 * *
186 \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
187 * *
188 ************************************************************************
189 -}
190
191 dsLExpr :: LHsExpr Id -> DsM CoreExpr
192
193 dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e
194
195 dsExpr :: HsExpr Id -> DsM CoreExpr
196 dsExpr (HsPar e) = dsLExpr e
197 dsExpr (ExprWithTySigOut e _) = dsLExpr e
198 dsExpr (HsVar var) = return (varToCoreExpr var) -- See Note [Desugaring vars]
199 dsExpr (HsIPVar _) = panic "dsExpr: HsIPVar"
200 dsExpr (HsLit lit) = dsLit lit
201 dsExpr (HsOverLit lit) = dsOverLit lit
202
203 dsExpr (HsWrap co_fn e)
204 = do { e' <- dsExpr e
205 ; wrapped_e <- dsHsWrapper co_fn e'
206 ; dflags <- getDynFlags
207 ; warnAboutIdentities dflags e' (exprType wrapped_e)
208 ; return wrapped_e }
209
210 dsExpr (NegApp expr neg_expr)
211 = App <$> dsExpr neg_expr <*> dsLExpr expr
212
213 dsExpr (HsLam a_Match)
214 = uncurry mkLams <$> matchWrapper LambdaExpr a_Match
215
216 dsExpr (HsLamCase arg matches)
217 = do { arg_var <- newSysLocalDs arg
218 ; ([discrim_var], matching_code) <- matchWrapper CaseAlt matches
219 ; return $ Lam arg_var $ bindNonRec discrim_var (Var arg_var) matching_code }
220
221 dsExpr (HsApp fun arg)
222 = mkCoreAppDs <$> dsLExpr fun <*> dsLExpr arg
223
224 dsExpr (HsUnboundVar _) = panic "dsExpr: HsUnboundVar"
225
226 {-
227 Note [Desugaring vars]
228 ~~~~~~~~~~~~~~~~~~~~~~
229 In one situation we can get a *coercion* variable in a HsVar, namely
230 the support method for an equality superclass:
231 class (a~b) => C a b where ...
232 instance (blah) => C (T a) (T b) where ..
233 Then we get
234 $dfCT :: forall ab. blah => C (T a) (T b)
235 $dfCT ab blah = MkC ($c$p1C a blah) ($cop a blah)
236
237 $c$p1C :: forall ab. blah => (T a ~ T b)
238 $c$p1C ab blah = let ...; g :: T a ~ T b = ... } in g
239
240 That 'g' in the 'in' part is an evidence variable, and when
241 converting to core it must become a CO.
242
243 Operator sections. At first it looks as if we can convert
244 \begin{verbatim}
245 (expr op)
246 \end{verbatim}
247 to
248 \begin{verbatim}
249 \x -> op expr x
250 \end{verbatim}
251
252 But no! expr might be a redex, and we can lose laziness badly this
253 way. Consider
254 \begin{verbatim}
255 map (expr op) xs
256 \end{verbatim}
257 for example. So we convert instead to
258 \begin{verbatim}
259 let y = expr in \x -> op y x
260 \end{verbatim}
261 If \tr{expr} is actually just a variable, say, then the simplifier
262 will sort it out.
263 -}
264
265 dsExpr (OpApp e1 op _ e2)
266 = -- for the type of y, we need the type of op's 2nd argument
267 mkCoreAppsDs <$> dsLExpr op <*> mapM dsLExpr [e1, e2]
268
269 dsExpr (SectionL expr op) -- Desugar (e !) to ((!) e)
270 = mkCoreAppDs <$> dsLExpr op <*> dsLExpr expr
271
272 -- dsLExpr (SectionR op expr) -- \ x -> op x expr
273 dsExpr (SectionR op expr) = do
274 core_op <- dsLExpr op
275 -- for the type of x, we need the type of op's 2nd argument
276 let (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
277 -- See comment with SectionL
278 y_core <- dsLExpr expr
279 x_id <- newSysLocalDs x_ty
280 y_id <- newSysLocalDs y_ty
281 return (bindNonRec y_id y_core $
282 Lam x_id (mkCoreAppsDs core_op [Var x_id, Var y_id]))
283
284 dsExpr (ExplicitTuple tup_args boxity)
285 = do { let go (lam_vars, args) (L _ (Missing ty))
286 -- For every missing expression, we need
287 -- another lambda in the desugaring.
288 = do { lam_var <- newSysLocalDs ty
289 ; return (lam_var : lam_vars, Var lam_var : args) }
290 go (lam_vars, args) (L _ (Present expr))
291 -- Expressions that are present don't generate
292 -- lambdas, just arguments.
293 = do { core_expr <- dsLExpr expr
294 ; return (lam_vars, core_expr : args) }
295
296 ; (lam_vars, args) <- foldM go ([], []) (reverse tup_args)
297 -- The reverse is because foldM goes left-to-right
298
299 ; return $ mkCoreLams lam_vars $
300 mkCoreConApps (tupleCon (boxityNormalTupleSort boxity) (length tup_args))
301 (map (Type . exprType) args ++ args) }
302
303 dsExpr (HsSCC cc expr@(L loc _)) = do
304 mod_name <- getModule
305 count <- goptM Opt_ProfCountEntries
306 uniq <- newUnique
307 Tick (ProfNote (mkUserCC cc mod_name loc uniq) count True) <$> dsLExpr expr
308
309 dsExpr (HsCoreAnn _ expr)
310 = dsLExpr expr
311
312 dsExpr (HsCase discrim matches)
313 = do { core_discrim <- dsLExpr discrim
314 ; ([discrim_var], matching_code) <- matchWrapper CaseAlt matches
315 ; return (bindNonRec discrim_var core_discrim matching_code) }
316
317 -- Pepe: The binds are in scope in the body but NOT in the binding group
318 -- This is to avoid silliness in breakpoints
319 dsExpr (HsLet binds body) = do
320 body' <- dsLExpr body
321 dsLocalBinds binds body'
322
323 -- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
324 -- because the interpretation of `stmts' depends on what sort of thing it is.
325 --
326 dsExpr (HsDo ListComp stmts res_ty) = dsListComp stmts res_ty
327 dsExpr (HsDo PArrComp stmts _) = dsPArrComp (map unLoc stmts)
328 dsExpr (HsDo DoExpr stmts _) = dsDo stmts
329 dsExpr (HsDo GhciStmtCtxt stmts _) = dsDo stmts
330 dsExpr (HsDo MDoExpr stmts _) = dsDo stmts
331 dsExpr (HsDo MonadComp stmts _) = dsMonadComp stmts
332
333 dsExpr (HsIf mb_fun guard_expr then_expr else_expr)
334 = do { pred <- dsLExpr guard_expr
335 ; b1 <- dsLExpr then_expr
336 ; b2 <- dsLExpr else_expr
337 ; case mb_fun of
338 Just fun -> do { core_fun <- dsExpr fun
339 ; return (mkCoreApps core_fun [pred,b1,b2]) }
340 Nothing -> return $ mkIfThenElse pred b1 b2 }
341
342 dsExpr (HsMultiIf res_ty alts)
343 | null alts
344 = mkErrorExpr
345
346 | otherwise
347 = do { match_result <- liftM (foldr1 combineMatchResults)
348 (mapM (dsGRHS IfAlt res_ty) alts)
349 ; error_expr <- mkErrorExpr
350 ; extractMatchResult match_result error_expr }
351 where
352 mkErrorExpr = mkErrorAppDs nON_EXHAUSTIVE_GUARDS_ERROR_ID res_ty
353 (ptext (sLit "multi-way if"))
354
355 {-
356 \noindent
357 \underline{\bf Various data construction things}
358 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
359 -}
360
361 dsExpr (ExplicitList elt_ty wit xs)
362 = dsExplicitList elt_ty wit xs
363
364 -- We desugar [:x1, ..., xn:] as
365 -- singletonP x1 +:+ ... +:+ singletonP xn
366 --
367 dsExpr (ExplicitPArr ty []) = do
368 emptyP <- dsDPHBuiltin emptyPVar
369 return (Var emptyP `App` Type ty)
370 dsExpr (ExplicitPArr ty xs) = do
371 singletonP <- dsDPHBuiltin singletonPVar
372 appP <- dsDPHBuiltin appPVar
373 xs' <- mapM dsLExpr xs
374 return . foldr1 (binary appP) $ map (unary singletonP) xs'
375 where
376 unary fn x = mkApps (Var fn) [Type ty, x]
377 binary fn x y = mkApps (Var fn) [Type ty, x, y]
378
379 dsExpr (ArithSeq expr witness seq)
380 = case witness of
381 Nothing -> dsArithSeq expr seq
382 Just fl -> do {
383 ; fl' <- dsExpr fl
384 ; newArithSeq <- dsArithSeq expr seq
385 ; return (App fl' newArithSeq)}
386
387 dsExpr (PArrSeq expr (FromTo from to))
388 = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, to]
389
390 dsExpr (PArrSeq expr (FromThenTo from thn to))
391 = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, thn, to]
392
393 dsExpr (PArrSeq _ _)
394 = panic "DsExpr.dsExpr: Infinite parallel array!"
395 -- the parser shouldn't have generated it and the renamer and typechecker
396 -- shouldn't have let it through
397
398 {-
399 \noindent
400 \underline{\bf Static Pointers}
401 ~~~~~~~~~~~~~~~
402 \begin{verbatim}
403 g = ... static f ...
404 ==>
405 sptEntry:N = StaticPtr
406 (fingerprintString "pkgId:module.sptEntry:N")
407 (StaticPtrInfo "current pkg id" "current module" "sptEntry:0")
408 f
409 g = ... sptEntry:N
410 \end{verbatim}
411 -}
412
413 dsExpr (HsStatic expr@(L loc _)) = do
414 expr_ds <- dsLExpr expr
415 let ty = exprType expr_ds
416 n' <- mkSptEntryName loc
417 static_binds_var <- dsGetStaticBindsVar
418
419 staticPtrTyCon <- dsLookupTyCon staticPtrTyConName
420 staticPtrInfoDataCon <- dsLookupDataCon staticPtrInfoDataConName
421 staticPtrDataCon <- dsLookupDataCon staticPtrDataConName
422 fingerprintDataCon <- dsLookupDataCon fingerprintDataConName
423
424 dflags <- getDynFlags
425 let (line, col) = case loc of
426 RealSrcSpan r -> ( srcLocLine $ realSrcSpanStart r
427 , srcLocCol $ realSrcSpanStart r
428 )
429 _ -> (0, 0)
430 srcLoc = mkCoreConApps (tupleCon BoxedTuple 2)
431 [ Type intTy , Type intTy
432 , mkIntExprInt dflags line, mkIntExprInt dflags col
433 ]
434 info <- mkConApp staticPtrInfoDataCon <$>
435 (++[srcLoc]) <$>
436 mapM mkStringExprFS
437 [ packageKeyFS $ modulePackageKey $ nameModule n'
438 , moduleNameFS $ moduleName $ nameModule n'
439 , occNameFS $ nameOccName n'
440 ]
441 let tvars = varSetElems $ tyVarsOfType ty
442 speTy = mkForAllTys tvars $ mkTyConApp staticPtrTyCon [ty]
443 speId = mkExportedLocalId VanillaId n' speTy
444 fp@(Fingerprint w0 w1) = fingerprintName $ idName speId
445 fp_core = mkConApp fingerprintDataCon
446 [ mkWord64LitWordRep dflags w0
447 , mkWord64LitWordRep dflags w1
448 ]
449 sp = mkConApp staticPtrDataCon [Type ty, fp_core, info, expr_ds]
450 liftIO $ modifyIORef static_binds_var ((fp, (speId, mkLams tvars sp)) :)
451 putSrcSpanDs loc $ return $ mkTyApps (Var speId) (map mkTyVarTy tvars)
452
453 where
454
455 -- | Choose either 'Word64#' or 'Word#' to represent the arguments of the
456 -- 'Fingerprint' data constructor.
457 mkWord64LitWordRep dflags
458 | platformWordSize (targetPlatform dflags) < 8 = mkWord64LitWord64
459 | otherwise = mkWordLit dflags . toInteger
460
461 fingerprintName :: Name -> Fingerprint
462 fingerprintName n = fingerprintString $ unpackFS $ concatFS
463 [ packageKeyFS $ modulePackageKey $ nameModule n
464 , fsLit ":"
465 , moduleNameFS (moduleName $ nameModule n)
466 , fsLit "."
467 , occNameFS $ occName n
468 ]
469
470 {-
471 \noindent
472 \underline{\bf Record construction and update}
473 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
474 For record construction we do this (assuming T has three arguments)
475 \begin{verbatim}
476 T { op2 = e }
477 ==>
478 let err = /\a -> recConErr a
479 T (recConErr t1 "M.lhs/230/op1")
480 e
481 (recConErr t1 "M.lhs/230/op3")
482 \end{verbatim}
483 @recConErr@ then converts its arugment string into a proper message
484 before printing it as
485 \begin{verbatim}
486 M.lhs, line 230: missing field op1 was evaluated
487 \end{verbatim}
488
489 We also handle @C{}@ as valid construction syntax for an unlabelled
490 constructor @C@, setting all of @C@'s fields to bottom.
491 -}
492
493 dsExpr (RecordCon (L _ data_con_id) con_expr rbinds) = do
494 con_expr' <- dsExpr con_expr
495 let
496 (arg_tys, _) = tcSplitFunTys (exprType con_expr')
497 -- A newtype in the corner should be opaque;
498 -- hence TcType.tcSplitFunTys
499
500 mk_arg (arg_ty, lbl) -- Selector id has the field label as its name
501 = case findField (rec_flds rbinds) lbl of
502 (rhs:rhss) -> ASSERT( null rhss )
503 dsLExpr rhs
504 [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (ppr lbl)
505 unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty Outputable.empty
506
507 labels = dataConFieldLabels (idDataCon data_con_id)
508 -- The data_con_id is guaranteed to be the wrapper id of the constructor
509
510 con_args <- if null labels
511 then mapM unlabelled_bottom arg_tys
512 else mapM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels)
513
514 return (mkCoreApps con_expr' con_args)
515
516 {-
517 Record update is a little harder. Suppose we have the decl:
518 \begin{verbatim}
519 data T = T1 {op1, op2, op3 :: Int}
520 | T2 {op4, op2 :: Int}
521 | T3
522 \end{verbatim}
523 Then we translate as follows:
524 \begin{verbatim}
525 r { op2 = e }
526 ===>
527 let op2 = e in
528 case r of
529 T1 op1 _ op3 -> T1 op1 op2 op3
530 T2 op4 _ -> T2 op4 op2
531 other -> recUpdError "M.lhs/230"
532 \end{verbatim}
533 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
534 RHSs, and do not generate a Core constructor application directly, because the constructor
535 might do some argument-evaluation first; and may have to throw away some
536 dictionaries.
537
538 Note [Update for GADTs]
539 ~~~~~~~~~~~~~~~~~~~~~~~
540 Consider
541 data T a b where
542 T1 { f1 :: a } :: T a Int
543
544 Then the wrapper function for T1 has type
545 $WT1 :: a -> T a Int
546 But if x::T a b, then
547 x { f1 = v } :: T a b (not T a Int!)
548 So we need to cast (T a Int) to (T a b). Sigh.
549 -}
550
551 dsExpr expr@(RecordUpd record_expr (HsRecFields { rec_flds = fields })
552 cons_to_upd in_inst_tys out_inst_tys)
553 | null fields
554 = dsLExpr record_expr
555 | otherwise
556 = ASSERT2( notNull cons_to_upd, ppr expr )
557
558 do { record_expr' <- dsLExpr record_expr
559 ; field_binds' <- mapM ds_field fields
560 ; let upd_fld_env :: NameEnv Id -- Maps field name to the LocalId of the field binding
561 upd_fld_env = mkNameEnv [(f,l) | (f,l,_) <- field_binds']
562
563 -- It's important to generate the match with matchWrapper,
564 -- and the right hand sides with applications of the wrapper Id
565 -- so that everything works when we are doing fancy unboxing on the
566 -- constructor aguments.
567 ; alts <- mapM (mk_alt upd_fld_env) cons_to_upd
568 ; ([discrim_var], matching_code)
569 <- matchWrapper RecUpd (MG { mg_alts = alts, mg_arg_tys = [in_ty]
570 , mg_res_ty = out_ty, mg_origin = FromSource })
571 -- FromSource is not strictly right, but we
572 -- want incomplete pattern-match warnings
573
574 ; return (add_field_binds field_binds' $
575 bindNonRec discrim_var record_expr' matching_code) }
576 where
577 ds_field :: LHsRecField Id (LHsExpr Id) -> DsM (Name, Id, CoreExpr)
578 -- Clone the Id in the HsRecField, because its Name is that
579 -- of the record selector, and we must not make that a lcoal binder
580 -- else we shadow other uses of the record selector
581 -- Hence 'lcl_id'. Cf Trac #2735
582 ds_field (L _ rec_field) = do { rhs <- dsLExpr (hsRecFieldArg rec_field)
583 ; let fld_id = unLoc (hsRecFieldId rec_field)
584 ; lcl_id <- newSysLocalDs (idType fld_id)
585 ; return (idName fld_id, lcl_id, rhs) }
586
587 add_field_binds [] expr = expr
588 add_field_binds ((_,b,r):bs) expr = bindNonRec b r (add_field_binds bs expr)
589
590 -- Awkwardly, for families, the match goes
591 -- from instance type to family type
592 tycon = dataConTyCon (head cons_to_upd)
593 in_ty = mkTyConApp tycon in_inst_tys
594 out_ty = mkFamilyTyConApp tycon out_inst_tys
595
596 mk_alt upd_fld_env con
597 = do { let (univ_tvs, ex_tvs, eq_spec,
598 theta, arg_tys, _) = dataConFullSig con
599 subst = mkTopTvSubst (univ_tvs `zip` in_inst_tys)
600
601 -- I'm not bothering to clone the ex_tvs
602 ; eqs_vars <- mapM newPredVarDs (substTheta subst (eqSpecPreds eq_spec))
603 ; theta_vars <- mapM newPredVarDs (substTheta subst theta)
604 ; arg_ids <- newSysLocalsDs (substTys subst arg_tys)
605 ; let val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
606 (dataConFieldLabels con) arg_ids
607 mk_val_arg field_name pat_arg_id
608 = nlHsVar (lookupNameEnv upd_fld_env field_name `orElse` pat_arg_id)
609 inst_con = noLoc $ HsWrap wrap (HsVar (dataConWrapId con))
610 -- Reconstruct with the WrapId so that unpacking happens
611 wrap = mkWpEvVarApps theta_vars <.>
612 mkWpTyApps (mkTyVarTys ex_tvs) <.>
613 mkWpTyApps [ty | (tv, ty) <- univ_tvs `zip` out_inst_tys
614 , not (tv `elemVarEnv` wrap_subst) ]
615 rhs = foldl (\a b -> nlHsApp a b) inst_con val_args
616
617 -- Tediously wrap the application in a cast
618 -- Note [Update for GADTs]
619 wrap_co = mkTcTyConAppCo Nominal tycon
620 [ lookup tv ty | (tv,ty) <- univ_tvs `zip` out_inst_tys ]
621 lookup univ_tv ty = case lookupVarEnv wrap_subst univ_tv of
622 Just co' -> co'
623 Nothing -> mkTcReflCo Nominal ty
624 wrap_subst = mkVarEnv [ (tv, mkTcSymCo (mkTcCoVarCo eq_var))
625 | ((tv,_),eq_var) <- eq_spec `zip` eqs_vars ]
626
627 pat = noLoc $ ConPatOut { pat_con = noLoc (RealDataCon con)
628 , pat_tvs = ex_tvs
629 , pat_dicts = eqs_vars ++ theta_vars
630 , pat_binds = emptyTcEvBinds
631 , pat_args = PrefixCon $ map nlVarPat arg_ids
632 , pat_arg_tys = in_inst_tys
633 , pat_wrap = idHsWrapper }
634 ; let wrapped_rhs | null eq_spec = rhs
635 | otherwise = mkLHsWrap (mkWpCast (mkTcSubCo wrap_co)) rhs
636 ; return (mkSimpleMatch [pat] wrapped_rhs) }
637
638 -- Here is where we desugar the Template Haskell brackets and escapes
639
640 -- Template Haskell stuff
641
642 dsExpr (HsRnBracketOut _ _) = panic "dsExpr HsRnBracketOut"
643 #ifdef GHCI
644 dsExpr (HsTcBracketOut x ps) = dsBracket x ps
645 #else
646 dsExpr (HsTcBracketOut _ _) = panic "dsExpr HsBracketOut"
647 #endif
648 dsExpr (HsSpliceE _ s) = pprPanic "dsExpr:splice" (ppr s)
649
650 -- Arrow notation extension
651 dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
652
653 -- Hpc Support
654
655 dsExpr (HsTick tickish e) = do
656 e' <- dsLExpr e
657 return (Tick tickish e')
658
659 -- There is a problem here. The then and else branches
660 -- have no free variables, so they are open to lifting.
661 -- We need someway of stopping this.
662 -- This will make no difference to binary coverage
663 -- (did you go here: YES or NO), but will effect accurate
664 -- tick counting.
665
666 dsExpr (HsBinTick ixT ixF e) = do
667 e2 <- dsLExpr e
668 do { ASSERT(exprType e2 `eqType` boolTy)
669 mkBinaryTickBox ixT ixF e2
670 }
671
672 -- HsSyn constructs that just shouldn't be here:
673 dsExpr (ExprWithTySig {}) = panic "dsExpr:ExprWithTySig"
674 dsExpr (HsBracket {}) = panic "dsExpr:HsBracket"
675 dsExpr (HsQuasiQuoteE {}) = panic "dsExpr:HsQuasiQuoteE"
676 dsExpr (HsArrApp {}) = panic "dsExpr:HsArrApp"
677 dsExpr (HsArrForm {}) = panic "dsExpr:HsArrForm"
678 dsExpr (HsTickPragma {}) = panic "dsExpr:HsTickPragma"
679 dsExpr (EWildPat {}) = panic "dsExpr:EWildPat"
680 dsExpr (EAsPat {}) = panic "dsExpr:EAsPat"
681 dsExpr (EViewPat {}) = panic "dsExpr:EViewPat"
682 dsExpr (ELazyPat {}) = panic "dsExpr:ELazyPat"
683 dsExpr (HsType {}) = panic "dsExpr:HsType"
684 dsExpr (HsDo {}) = panic "dsExpr:HsDo"
685
686
687 findField :: [LHsRecField Id arg] -> Name -> [arg]
688 findField rbinds lbl
689 = [rhs | L _ (HsRecField { hsRecFieldId = id, hsRecFieldArg = rhs }) <- rbinds
690 , lbl == idName (unLoc id) ]
691
692 {-
693 %--------------------------------------------------------------------
694
695 Note [Desugaring explicit lists]
696 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
697 Explicit lists are desugared in a cleverer way to prevent some
698 fruitless allocations. Essentially, whenever we see a list literal
699 [x_1, ..., x_n] we:
700
701 1. Find the tail of the list that can be allocated statically (say
702 [x_k, ..., x_n]) by later stages and ensure we desugar that
703 normally: this makes sure that we don't cause a code size increase
704 by having the cons in that expression fused (see later) and hence
705 being unable to statically allocate any more
706
707 2. For the prefix of the list which cannot be allocated statically,
708 say [x_1, ..., x_(k-1)], we turn it into an expression involving
709 build so that if we find any foldrs over it it will fuse away
710 entirely!
711
712 So in this example we will desugar to:
713 build (\c n -> x_1 `c` x_2 `c` .... `c` foldr c n [x_k, ..., x_n]
714
715 If fusion fails to occur then build will get inlined and (since we
716 defined a RULE for foldr (:) []) we will get back exactly the
717 normal desugaring for an explicit list.
718
719 This optimisation can be worth a lot: up to 25% of the total
720 allocation in some nofib programs. Specifically
721
722 Program Size Allocs Runtime CompTime
723 rewrite +0.0% -26.3% 0.02 -1.8%
724 ansi -0.3% -13.8% 0.00 +0.0%
725 lift +0.0% -8.7% 0.00 -2.3%
726
727 Of course, if rules aren't turned on then there is pretty much no
728 point doing this fancy stuff, and it may even be harmful.
729
730 =======> Note by SLPJ Dec 08.
731
732 I'm unconvinced that we should *ever* generate a build for an explicit
733 list. See the comments in GHC.Base about the foldr/cons rule, which
734 points out that (foldr k z [a,b,c]) may generate *much* less code than
735 (a `k` b `k` c `k` z).
736
737 Furthermore generating builds messes up the LHS of RULES.
738 Example: the foldr/single rule in GHC.Base
739 foldr k z [x] = ...
740 We do not want to generate a build invocation on the LHS of this RULE!
741
742 We fix this by disabling rules in rule LHSs, and testing that
743 flag here; see Note [Desugaring RULE left hand sides] in Desugar
744
745 To test this I've added a (static) flag -fsimple-list-literals, which
746 makes all list literals be generated via the simple route.
747 -}
748
749 dsExplicitList :: PostTc Id Type -> Maybe (SyntaxExpr Id) -> [LHsExpr Id]
750 -> DsM CoreExpr
751 -- See Note [Desugaring explicit lists]
752 dsExplicitList elt_ty Nothing xs
753 = do { dflags <- getDynFlags
754 ; xs' <- mapM dsLExpr xs
755 ; let (dynamic_prefix, static_suffix) = spanTail is_static xs'
756 ; if gopt Opt_SimpleListLiterals dflags -- -fsimple-list-literals
757 || not (gopt Opt_EnableRewriteRules dflags) -- Rewrite rules off
758 -- Don't generate a build if there are no rules to eliminate it!
759 -- See Note [Desugaring RULE left hand sides] in Desugar
760 || null dynamic_prefix -- Avoid build (\c n. foldr c n xs)!
761 then return $ mkListExpr elt_ty xs'
762 else mkBuildExpr elt_ty (mkSplitExplicitList dynamic_prefix static_suffix) }
763 where
764 is_static :: CoreExpr -> Bool
765 is_static e = all is_static_var (varSetElems (exprFreeVars e))
766
767 is_static_var :: Var -> Bool
768 is_static_var v
769 | isId v = isExternalName (idName v) -- Top-level things are given external names
770 | otherwise = False -- Type variables
771
772 mkSplitExplicitList prefix suffix (c, _) (n, n_ty)
773 = do { let suffix' = mkListExpr elt_ty suffix
774 ; folded_suffix <- mkFoldrExpr elt_ty n_ty (Var c) (Var n) suffix'
775 ; return (foldr (App . App (Var c)) folded_suffix prefix) }
776
777 dsExplicitList elt_ty (Just fln) xs
778 = do { fln' <- dsExpr fln
779 ; list <- dsExplicitList elt_ty Nothing xs
780 ; dflags <- getDynFlags
781 ; return (App (App fln' (mkIntExprInt dflags (length xs))) list) }
782
783 spanTail :: (a -> Bool) -> [a] -> ([a], [a])
784 spanTail f xs = (reverse rejected, reverse satisfying)
785 where (satisfying, rejected) = span f $ reverse xs
786
787 dsArithSeq :: PostTcExpr -> (ArithSeqInfo Id) -> DsM CoreExpr
788 dsArithSeq expr (From from)
789 = App <$> dsExpr expr <*> dsLExpr from
790 dsArithSeq expr (FromTo from to)
791 = do dflags <- getDynFlags
792 warnAboutEmptyEnumerations dflags from Nothing to
793 expr' <- dsExpr expr
794 from' <- dsLExpr from
795 to' <- dsLExpr to
796 return $ mkApps expr' [from', to']
797 dsArithSeq expr (FromThen from thn)
798 = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, thn]
799 dsArithSeq expr (FromThenTo from thn to)
800 = do dflags <- getDynFlags
801 warnAboutEmptyEnumerations dflags from (Just thn) to
802 expr' <- dsExpr expr
803 from' <- dsLExpr from
804 thn' <- dsLExpr thn
805 to' <- dsLExpr to
806 return $ mkApps expr' [from', thn', to']
807
808 {-
809 Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
810 handled in DsListComp). Basically does the translation given in the
811 Haskell 98 report:
812 -}
813
814 dsDo :: [ExprLStmt Id] -> DsM CoreExpr
815 dsDo stmts
816 = goL stmts
817 where
818 goL [] = panic "dsDo"
819 goL (L loc stmt:lstmts) = putSrcSpanDs loc (go loc stmt lstmts)
820
821 go _ (LastStmt body _) stmts
822 = ASSERT( null stmts ) dsLExpr body
823 -- The 'return' op isn't used for 'do' expressions
824
825 go _ (BodyStmt rhs then_expr _ _) stmts
826 = do { rhs2 <- dsLExpr rhs
827 ; warnDiscardedDoBindings rhs (exprType rhs2)
828 ; then_expr2 <- dsExpr then_expr
829 ; rest <- goL stmts
830 ; return (mkApps then_expr2 [rhs2, rest]) }
831
832 go _ (LetStmt binds) stmts
833 = do { rest <- goL stmts
834 ; dsLocalBinds binds rest }
835
836 go _ (BindStmt pat rhs bind_op fail_op) stmts
837 = do { body <- goL stmts
838 ; rhs' <- dsLExpr rhs
839 ; bind_op' <- dsExpr bind_op
840 ; var <- selectSimpleMatchVarL pat
841 ; let bind_ty = exprType bind_op' -- rhs -> (pat -> res1) -> res2
842 res1_ty = funResultTy (funArgTy (funResultTy bind_ty))
843 ; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat
844 res1_ty (cantFailMatchResult body)
845 ; match_code <- handle_failure pat match fail_op
846 ; return (mkApps bind_op' [rhs', Lam var match_code]) }
847
848 go loc (RecStmt { recS_stmts = rec_stmts, recS_later_ids = later_ids
849 , recS_rec_ids = rec_ids, recS_ret_fn = return_op
850 , recS_mfix_fn = mfix_op, recS_bind_fn = bind_op
851 , recS_rec_rets = rec_rets, recS_ret_ty = body_ty }) stmts
852 = goL (new_bind_stmt : stmts) -- rec_ids can be empty; eg rec { print 'x' }
853 where
854 new_bind_stmt = L loc $ BindStmt (mkBigLHsPatTup later_pats)
855 mfix_app bind_op
856 noSyntaxExpr -- Tuple cannot fail
857
858 tup_ids = rec_ids ++ filterOut (`elem` rec_ids) later_ids
859 tup_ty = mkBigCoreTupTy (map idType tup_ids) -- Deals with singleton case
860 rec_tup_pats = map nlVarPat tup_ids
861 later_pats = rec_tup_pats
862 rets = map noLoc rec_rets
863 mfix_app = nlHsApp (noLoc mfix_op) mfix_arg
864 mfix_arg = noLoc $ HsLam (MG { mg_alts = [mkSimpleMatch [mfix_pat] body]
865 , mg_arg_tys = [tup_ty], mg_res_ty = body_ty
866 , mg_origin = Generated })
867 mfix_pat = noLoc $ LazyPat $ mkBigLHsPatTup rec_tup_pats
868 body = noLoc $ HsDo DoExpr (rec_stmts ++ [ret_stmt]) body_ty
869 ret_app = nlHsApp (noLoc return_op) (mkBigLHsTup rets)
870 ret_stmt = noLoc $ mkLastStmt ret_app
871 -- This LastStmt will be desugared with dsDo,
872 -- which ignores the return_op in the LastStmt,
873 -- so we must apply the return_op explicitly
874
875 go _ (ParStmt {}) _ = panic "dsDo ParStmt"
876 go _ (TransStmt {}) _ = panic "dsDo TransStmt"
877
878 handle_failure :: LPat Id -> MatchResult -> SyntaxExpr Id -> DsM CoreExpr
879 -- In a do expression, pattern-match failure just calls
880 -- the monadic 'fail' rather than throwing an exception
881 handle_failure pat match fail_op
882 | matchCanFail match
883 = do { fail_op' <- dsExpr fail_op
884 ; dflags <- getDynFlags
885 ; fail_msg <- mkStringExpr (mk_fail_msg dflags pat)
886 ; extractMatchResult match (App fail_op' fail_msg) }
887 | otherwise
888 = extractMatchResult match (error "It can't fail")
889
890 mk_fail_msg :: DynFlags -> Located e -> String
891 mk_fail_msg dflags pat = "Pattern match failure in do expression at " ++
892 showPpr dflags (getLoc pat)
893
894 {-
895 ************************************************************************
896 * *
897 \subsection{Errors and contexts}
898 * *
899 ************************************************************************
900 -}
901
902 -- Warn about certain types of values discarded in monadic bindings (#3263)
903 warnDiscardedDoBindings :: LHsExpr Id -> Type -> DsM ()
904 warnDiscardedDoBindings rhs rhs_ty
905 | Just (m_ty, elt_ty) <- tcSplitAppTy_maybe rhs_ty
906 = do { warn_unused <- woptM Opt_WarnUnusedDoBind
907 ; warn_wrong <- woptM Opt_WarnWrongDoBind
908 ; when (warn_unused || warn_wrong) $
909 do { fam_inst_envs <- dsGetFamInstEnvs
910 ; let norm_elt_ty = topNormaliseType fam_inst_envs elt_ty
911
912 -- Warn about discarding non-() things in 'monadic' binding
913 ; if warn_unused && not (isUnitTy norm_elt_ty)
914 then warnDs (badMonadBind rhs elt_ty
915 (ptext (sLit "-fno-warn-unused-do-bind")))
916 else
917
918 -- Warn about discarding m a things in 'monadic' binding of the same type,
919 -- but only if we didn't already warn due to Opt_WarnUnusedDoBind
920 when warn_wrong $
921 do { case tcSplitAppTy_maybe norm_elt_ty of
922 Just (elt_m_ty, _)
923 | m_ty `eqType` topNormaliseType fam_inst_envs elt_m_ty
924 -> warnDs (badMonadBind rhs elt_ty
925 (ptext (sLit "-fno-warn-wrong-do-bind")))
926 _ -> return () } } }
927
928 | otherwise -- RHS does have type of form (m ty), which is weird
929 = return () -- but at lesat this warning is irrelevant
930
931 badMonadBind :: LHsExpr Id -> Type -> SDoc -> SDoc
932 badMonadBind rhs elt_ty flag_doc
933 = vcat [ hang (ptext (sLit "A do-notation statement discarded a result of type"))
934 2 (quotes (ppr elt_ty))
935 , hang (ptext (sLit "Suppress this warning by saying"))
936 2 (quotes $ ptext (sLit "_ <-") <+> ppr rhs)
937 , ptext (sLit "or by using the flag") <+> flag_doc ]
938
939 {-
940 ************************************************************************
941 * *
942 \subsection{Static pointers}
943 * *
944 ************************************************************************
945 -}
946
947 -- | Creates an name for an entry in the Static Pointer Table.
948 --
949 -- The name has the form @sptEntry:<N>@ where @<N>@ is generated from a
950 -- per-module counter.
951 --
952 mkSptEntryName :: SrcSpan -> DsM Name
953 mkSptEntryName loc = do
954 uniq <- newUnique
955 mod <- getModule
956 occ <- mkWrapperName "sptEntry"
957 return $ mkExternalName uniq mod occ loc
958 where
959 mkWrapperName what
960 = do dflags <- getDynFlags
961 thisMod <- getModule
962 let -- Note [Generating fresh names for ccall wrapper]
963 -- in compiler/typecheck/TcEnv.hs
964 wrapperRef = nextWrapperNum dflags
965 wrapperNum <- liftIO $ atomicModifyIORef wrapperRef $ \mod_env ->
966 let num = lookupWithDefaultModuleEnv mod_env 0 thisMod
967 in (extendModuleEnv mod_env thisMod (num+1), num)
968 return $ mkVarOcc $ what ++ ":" ++ show wrapperNum