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