Remove fun_infix from Funbind, as it is now in Match
[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 }) 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 )) 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 e@(HsApp fun arg)
221 = mkCoreAppDs (text "HsApp" <+> ppr e) <$> 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 e@(OpApp e1 op _ e2)
264 = -- for the type of y, we need the type of op's 2nd argument
265 mkCoreAppsDs (text "opapp" <+> ppr e) <$> dsLExpr op <*> mapM dsLExpr [e1, e2]
266
267 dsExpr (SectionL expr op) -- Desugar (e !) to ((!) e)
268 = mkCoreAppDs (text "sectionl" <+> ppr expr) <$> dsLExpr op <*> dsLExpr expr
269
270 -- dsLExpr (SectionR op expr) -- \ x -> op x expr
271 dsExpr e@(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 (text "sectionr" <+> ppr e) 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 _ con_expr rbinds labels) = 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
511 con_args <- if null labels
512 then mapM unlabelled_bottom arg_tys
513 else mapM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels)
514
515 return (mkCoreApps con_expr' con_args)
516
517 {-
518 Record update is a little harder. Suppose we have the decl:
519 \begin{verbatim}
520 data T = T1 {op1, op2, op3 :: Int}
521 | T2 {op4, op2 :: Int}
522 | T3
523 \end{verbatim}
524 Then we translate as follows:
525 \begin{verbatim}
526 r { op2 = e }
527 ===>
528 let op2 = e in
529 case r of
530 T1 op1 _ op3 -> T1 op1 op2 op3
531 T2 op4 _ -> T2 op4 op2
532 other -> recUpdError "M.hs/230"
533 \end{verbatim}
534 It's important that we use the constructor Ids for @T1@, @T2@ etc on the
535 RHSs, and do not generate a Core constructor application directly, because the constructor
536 might do some argument-evaluation first; and may have to throw away some
537 dictionaries.
538
539 Note [Update for GADTs]
540 ~~~~~~~~~~~~~~~~~~~~~~~
541 Consider
542 data T a b where
543 T1 { f1 :: a } :: T a Int
544
545 Then the wrapper function for T1 has type
546 $WT1 :: a -> T a Int
547 But if x::T a b, then
548 x { f1 = v } :: T a b (not T a Int!)
549 So we need to cast (T a Int) to (T a b). Sigh.
550 -}
551
552 dsExpr expr@(RecordUpd record_expr fields
553 cons_to_upd in_inst_tys out_inst_tys dict_req_wrap )
554 | null fields
555 = dsLExpr record_expr
556 | otherwise
557 = ASSERT2( notNull cons_to_upd, ppr expr )
558
559 do { record_expr' <- dsLExpr record_expr
560 ; field_binds' <- mapM ds_field fields
561 ; let upd_fld_env :: NameEnv Id -- Maps field name to the LocalId of the field binding
562 upd_fld_env = mkNameEnv [(f,l) | (f,l,_) <- field_binds']
563
564 -- It's important to generate the match with matchWrapper,
565 -- and the right hand sides with applications of the wrapper Id
566 -- so that everything works when we are doing fancy unboxing on the
567 -- constructor aguments.
568 ; alts <- mapM (mk_alt upd_fld_env) cons_to_upd
569 ; ([discrim_var], matching_code)
570 <- matchWrapper RecUpd (MG { mg_alts = alts, mg_arg_tys = [in_ty]
571 , mg_res_ty = out_ty, mg_origin = FromSource })
572 -- FromSource is not strictly right, but we
573 -- want incomplete pattern-match warnings
574
575 ; return (add_field_binds field_binds' $
576 bindNonRec discrim_var record_expr' matching_code) }
577 where
578 ds_field :: LHsRecUpdField Id -> DsM (Name, Id, CoreExpr)
579 -- Clone the Id in the HsRecField, because its Name is that
580 -- of the record selector, and we must not make that a local binder
581 -- else we shadow other uses of the record selector
582 -- Hence 'lcl_id'. Cf Trac #2735
583 ds_field (L _ rec_field) = do { rhs <- dsLExpr (hsRecFieldArg rec_field)
584 ; let fld_id = unLoc (hsRecUpdFieldId rec_field)
585 ; lcl_id <- newSysLocalDs (idType fld_id)
586 ; return (idName fld_id, lcl_id, rhs) }
587
588 add_field_binds [] expr = expr
589 add_field_binds ((_,b,r):bs) expr = bindNonRec b r (add_field_binds bs expr)
590
591 -- Awkwardly, for families, the match goes
592 -- from instance type to family type
593 (in_ty, out_ty) =
594 case (head cons_to_upd) of
595 RealDataCon data_con ->
596 let tycon = dataConTyCon data_con in
597 (mkTyConApp tycon in_inst_tys, mkFamilyTyConApp tycon out_inst_tys)
598 PatSynCon pat_syn ->
599 (patSynInstResTy pat_syn in_inst_tys
600 , patSynInstResTy pat_syn out_inst_tys)
601 mk_alt upd_fld_env con
602 = do { let (univ_tvs, ex_tvs, eq_spec,
603 prov_theta, _req_theta, arg_tys, _) = conLikeFullSig con
604 subst = mkTopTvSubst (univ_tvs `zip` in_inst_tys)
605
606 -- I'm not bothering to clone the ex_tvs
607 ; eqs_vars <- mapM newPredVarDs (substTheta subst (eqSpecPreds eq_spec))
608 ; theta_vars <- mapM newPredVarDs (substTheta subst prov_theta)
609 ; arg_ids <- newSysLocalsDs (substTys subst arg_tys)
610 ; let field_labels = conLikeFieldLabels con
611 val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
612 field_labels arg_ids
613 mk_val_arg fl pat_arg_id
614 = nlHsVar (lookupNameEnv upd_fld_env (flSelector fl) `orElse` pat_arg_id)
615 -- SAFE: the typechecker will complain if the synonym is
616 -- not bidirectional
617 wrap_id = expectJust "dsExpr:mk_alt" (conLikeWrapId_maybe con)
618 inst_con = noLoc $ HsWrap wrap (HsVar wrap_id)
619 -- Reconstruct with the WrapId so that unpacking happens
620 -- The order here is because of the order in `TcPatSyn`.
621 wrap =
622 dict_req_wrap <.>
623 mkWpEvVarApps theta_vars <.>
624 mkWpTyApps (mkTyVarTys ex_tvs) <.>
625 mkWpTyApps [ty | (tv, ty) <- univ_tvs `zip` out_inst_tys
626 , not (tv `elemVarEnv` wrap_subst) ]
627 rhs = foldl (\a b -> nlHsApp a b) inst_con val_args
628
629 -- Tediously wrap the application in a cast
630 -- Note [Update for GADTs]
631 wrapped_rhs =
632 case con of
633 RealDataCon data_con ->
634 let
635 wrap_co =
636 mkTcTyConAppCo Nominal
637 (dataConTyCon data_con)
638 [ lookup tv ty
639 | (tv,ty) <- univ_tvs `zip` out_inst_tys ]
640 lookup univ_tv ty =
641 case lookupVarEnv wrap_subst univ_tv of
642 Just co' -> co'
643 Nothing -> mkTcReflCo Nominal ty
644 in if null eq_spec
645 then rhs
646 else mkLHsWrap (mkWpCast (mkTcSubCo wrap_co)) rhs
647 -- eq_spec is always null for a PatSynCon
648 PatSynCon _ -> rhs
649
650 wrap_subst =
651 mkVarEnv [ (tv, mkTcSymCo (mkTcCoVarCo eq_var))
652 | ((tv,_),eq_var) <- eq_spec `zip` eqs_vars ]
653
654 req_wrap = dict_req_wrap <.> mkWpTyApps in_inst_tys
655 pat = noLoc $ ConPatOut { pat_con = noLoc con
656 , pat_tvs = ex_tvs
657 , pat_dicts = eqs_vars ++ theta_vars
658 , pat_binds = emptyTcEvBinds
659 , pat_args = PrefixCon $ map nlVarPat arg_ids
660 , pat_arg_tys = in_inst_tys
661 , pat_wrap = req_wrap }
662
663 ; return (mkSimpleMatch [pat] wrapped_rhs) }
664
665 -- Here is where we desugar the Template Haskell brackets and escapes
666
667 -- Template Haskell stuff
668
669 dsExpr (HsRnBracketOut _ _) = panic "dsExpr HsRnBracketOut"
670 dsExpr (HsTcBracketOut x ps) = dsBracket x ps
671 dsExpr (HsSpliceE s) = pprPanic "dsExpr:splice" (ppr s)
672
673 -- Arrow notation extension
674 dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
675
676 -- Hpc Support
677
678 dsExpr (HsTick tickish e) = do
679 e' <- dsLExpr e
680 return (Tick tickish e')
681
682 -- There is a problem here. The then and else branches
683 -- have no free variables, so they are open to lifting.
684 -- We need someway of stopping this.
685 -- This will make no difference to binary coverage
686 -- (did you go here: YES or NO), but will effect accurate
687 -- tick counting.
688
689 dsExpr (HsBinTick ixT ixF e) = do
690 e2 <- dsLExpr e
691 do { ASSERT(exprType e2 `eqType` boolTy)
692 mkBinaryTickBox ixT ixF e2
693 }
694
695 dsExpr (HsTickPragma _ _ expr) = do
696 dflags <- getDynFlags
697 if gopt Opt_Hpc dflags
698 then panic "dsExpr:HsTickPragma"
699 else dsLExpr expr
700
701 -- HsSyn constructs that just shouldn't be here:
702 dsExpr (ExprWithTySig {}) = panic "dsExpr:ExprWithTySig"
703 dsExpr (HsBracket {}) = panic "dsExpr:HsBracket"
704 dsExpr (HsArrApp {}) = panic "dsExpr:HsArrApp"
705 dsExpr (HsArrForm {}) = panic "dsExpr:HsArrForm"
706 dsExpr (EWildPat {}) = panic "dsExpr:EWildPat"
707 dsExpr (EAsPat {}) = panic "dsExpr:EAsPat"
708 dsExpr (EViewPat {}) = panic "dsExpr:EViewPat"
709 dsExpr (ELazyPat {}) = panic "dsExpr:ELazyPat"
710 dsExpr (HsType {}) = panic "dsExpr:HsType"
711 dsExpr (HsDo {}) = panic "dsExpr:HsDo"
712 dsExpr (HsRecFld {}) = panic "dsExpr:HsRecFld"
713
714
715 findField :: [LHsRecField Id arg] -> Name -> [arg]
716 findField rbinds sel
717 = [hsRecFieldArg fld | L _ fld <- rbinds
718 , sel == idName (unLoc $ hsRecFieldId fld) ]
719
720 {-
721 %--------------------------------------------------------------------
722
723 Note [Desugaring explicit lists]
724 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
725 Explicit lists are desugared in a cleverer way to prevent some
726 fruitless allocations. Essentially, whenever we see a list literal
727 [x_1, ..., x_n] we:
728
729 1. Find the tail of the list that can be allocated statically (say
730 [x_k, ..., x_n]) by later stages and ensure we desugar that
731 normally: this makes sure that we don't cause a code size increase
732 by having the cons in that expression fused (see later) and hence
733 being unable to statically allocate any more
734
735 2. For the prefix of the list which cannot be allocated statically,
736 say [x_1, ..., x_(k-1)], we turn it into an expression involving
737 build so that if we find any foldrs over it it will fuse away
738 entirely!
739
740 So in this example we will desugar to:
741 build (\c n -> x_1 `c` x_2 `c` .... `c` foldr c n [x_k, ..., x_n]
742
743 If fusion fails to occur then build will get inlined and (since we
744 defined a RULE for foldr (:) []) we will get back exactly the
745 normal desugaring for an explicit list.
746
747 This optimisation can be worth a lot: up to 25% of the total
748 allocation in some nofib programs. Specifically
749
750 Program Size Allocs Runtime CompTime
751 rewrite +0.0% -26.3% 0.02 -1.8%
752 ansi -0.3% -13.8% 0.00 +0.0%
753 lift +0.0% -8.7% 0.00 -2.3%
754
755 Of course, if rules aren't turned on then there is pretty much no
756 point doing this fancy stuff, and it may even be harmful.
757
758 =======> Note by SLPJ Dec 08.
759
760 I'm unconvinced that we should *ever* generate a build for an explicit
761 list. See the comments in GHC.Base about the foldr/cons rule, which
762 points out that (foldr k z [a,b,c]) may generate *much* less code than
763 (a `k` b `k` c `k` z).
764
765 Furthermore generating builds messes up the LHS of RULES.
766 Example: the foldr/single rule in GHC.Base
767 foldr k z [x] = ...
768 We do not want to generate a build invocation on the LHS of this RULE!
769
770 We fix this by disabling rules in rule LHSs, and testing that
771 flag here; see Note [Desugaring RULE left hand sides] in Desugar
772
773 To test this I've added a (static) flag -fsimple-list-literals, which
774 makes all list literals be generated via the simple route.
775 -}
776
777 dsExplicitList :: PostTc Id Type -> Maybe (SyntaxExpr Id) -> [LHsExpr Id]
778 -> DsM CoreExpr
779 -- See Note [Desugaring explicit lists]
780 dsExplicitList elt_ty Nothing xs
781 = do { dflags <- getDynFlags
782 ; xs' <- mapM dsLExpr xs
783 ; let (dynamic_prefix, static_suffix) = spanTail is_static xs'
784 ; if gopt Opt_SimpleListLiterals dflags -- -fsimple-list-literals
785 || not (gopt Opt_EnableRewriteRules dflags) -- Rewrite rules off
786 -- Don't generate a build if there are no rules to eliminate it!
787 -- See Note [Desugaring RULE left hand sides] in Desugar
788 || null dynamic_prefix -- Avoid build (\c n. foldr c n xs)!
789 then return $ mkListExpr elt_ty xs'
790 else mkBuildExpr elt_ty (mkSplitExplicitList dynamic_prefix static_suffix) }
791 where
792 is_static :: CoreExpr -> Bool
793 is_static e = all is_static_var (varSetElems (exprFreeVars e))
794
795 is_static_var :: Var -> Bool
796 is_static_var v
797 | isId v = isExternalName (idName v) -- Top-level things are given external names
798 | otherwise = False -- Type variables
799
800 mkSplitExplicitList prefix suffix (c, _) (n, n_ty)
801 = do { let suffix' = mkListExpr elt_ty suffix
802 ; folded_suffix <- mkFoldrExpr elt_ty n_ty (Var c) (Var n) suffix'
803 ; return (foldr (App . App (Var c)) folded_suffix prefix) }
804
805 dsExplicitList elt_ty (Just fln) xs
806 = do { fln' <- dsExpr fln
807 ; list <- dsExplicitList elt_ty Nothing xs
808 ; dflags <- getDynFlags
809 ; return (App (App fln' (mkIntExprInt dflags (length xs))) list) }
810
811 spanTail :: (a -> Bool) -> [a] -> ([a], [a])
812 spanTail f xs = (reverse rejected, reverse satisfying)
813 where (satisfying, rejected) = span f $ reverse xs
814
815 dsArithSeq :: PostTcExpr -> (ArithSeqInfo Id) -> DsM CoreExpr
816 dsArithSeq expr (From from)
817 = App <$> dsExpr expr <*> dsLExpr from
818 dsArithSeq expr (FromTo from to)
819 = do dflags <- getDynFlags
820 warnAboutEmptyEnumerations dflags from Nothing to
821 expr' <- dsExpr expr
822 from' <- dsLExpr from
823 to' <- dsLExpr to
824 return $ mkApps expr' [from', to']
825 dsArithSeq expr (FromThen from thn)
826 = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, thn]
827 dsArithSeq expr (FromThenTo from thn to)
828 = do dflags <- getDynFlags
829 warnAboutEmptyEnumerations dflags from (Just thn) to
830 expr' <- dsExpr expr
831 from' <- dsLExpr from
832 thn' <- dsLExpr thn
833 to' <- dsLExpr to
834 return $ mkApps expr' [from', thn', to']
835
836 {-
837 Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
838 handled in DsListComp). Basically does the translation given in the
839 Haskell 98 report:
840 -}
841
842 dsDo :: [ExprLStmt Id] -> DsM CoreExpr
843 dsDo stmts
844 = goL stmts
845 where
846 goL [] = panic "dsDo"
847 goL (L loc stmt:lstmts) = putSrcSpanDs loc (go loc stmt lstmts)
848
849 go _ (LastStmt body _ _) stmts
850 = ASSERT( null stmts ) dsLExpr body
851 -- The 'return' op isn't used for 'do' expressions
852
853 go _ (BodyStmt rhs then_expr _ _) stmts
854 = do { rhs2 <- dsLExpr rhs
855 ; warnDiscardedDoBindings rhs (exprType rhs2)
856 ; then_expr2 <- dsExpr then_expr
857 ; rest <- goL stmts
858 ; return (mkApps then_expr2 [rhs2, rest]) }
859
860 go _ (LetStmt binds) stmts
861 = do { rest <- goL stmts
862 ; dsLocalBinds binds rest }
863
864 go _ (BindStmt pat rhs bind_op fail_op) stmts
865 = do { body <- goL stmts
866 ; rhs' <- dsLExpr rhs
867 ; bind_op' <- dsExpr bind_op
868 ; var <- selectSimpleMatchVarL pat
869 ; let bind_ty = exprType bind_op' -- rhs -> (pat -> res1) -> res2
870 res1_ty = funResultTy (funArgTy (funResultTy bind_ty))
871 ; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat
872 res1_ty (cantFailMatchResult body)
873 ; match_code <- handle_failure pat match fail_op
874 ; return (mkApps bind_op' [rhs', Lam var match_code]) }
875
876 go _ (ApplicativeStmt args mb_join body_ty) stmts
877 = do {
878 let
879 (pats, rhss) = unzip (map (do_arg . snd) args)
880
881 do_arg (ApplicativeArgOne pat expr) =
882 (pat, dsLExpr expr)
883 do_arg (ApplicativeArgMany stmts ret pat) =
884 (pat, dsDo (stmts ++ [noLoc $ mkLastStmt (noLoc ret)]))
885
886 arg_tys = map hsLPatType pats
887
888 ; rhss' <- sequence rhss
889 ; ops' <- mapM dsExpr (map fst args)
890
891 ; let body' = noLoc $ HsDo DoExpr stmts body_ty
892
893 ; let fun = L noSrcSpan $ HsLam $
894 MG { mg_alts = [mkSimpleMatch pats body']
895 , mg_arg_tys = arg_tys
896 , mg_res_ty = body_ty
897 , mg_origin = Generated }
898
899 ; fun' <- dsLExpr fun
900 ; let mk_ap_call l (op,r) = mkApps op [l,r]
901 expr = foldl mk_ap_call fun' (zip ops' rhss')
902 ; case mb_join of
903 Nothing -> return expr
904 Just join_op ->
905 do { join_op' <- dsExpr join_op
906 ; return (App join_op' expr) } }
907
908 go loc (RecStmt { recS_stmts = rec_stmts, recS_later_ids = later_ids
909 , recS_rec_ids = rec_ids, recS_ret_fn = return_op
910 , recS_mfix_fn = mfix_op, recS_bind_fn = bind_op
911 , recS_rec_rets = rec_rets, recS_ret_ty = body_ty }) stmts
912 = goL (new_bind_stmt : stmts) -- rec_ids can be empty; eg rec { print 'x' }
913 where
914 new_bind_stmt = L loc $ BindStmt (mkBigLHsPatTupId later_pats)
915 mfix_app bind_op
916 noSyntaxExpr -- Tuple cannot fail
917
918 tup_ids = rec_ids ++ filterOut (`elem` rec_ids) later_ids
919 tup_ty = mkBigCoreTupTy (map idType tup_ids) -- Deals with singleton case
920 rec_tup_pats = map nlVarPat tup_ids
921 later_pats = rec_tup_pats
922 rets = map noLoc rec_rets
923 mfix_app = nlHsApp (noLoc mfix_op) mfix_arg
924 mfix_arg = noLoc $ HsLam (MG { mg_alts = [mkSimpleMatch [mfix_pat] body]
925 , mg_arg_tys = [tup_ty], mg_res_ty = body_ty
926 , mg_origin = Generated })
927 mfix_pat = noLoc $ LazyPat $ mkBigLHsPatTupId rec_tup_pats
928 body = noLoc $ HsDo DoExpr (rec_stmts ++ [ret_stmt]) body_ty
929 ret_app = nlHsApp (noLoc return_op) (mkBigLHsTupId rets)
930 ret_stmt = noLoc $ mkLastStmt ret_app
931 -- This LastStmt will be desugared with dsDo,
932 -- which ignores the return_op in the LastStmt,
933 -- so we must apply the return_op explicitly
934
935 go _ (ParStmt {}) _ = panic "dsDo ParStmt"
936 go _ (TransStmt {}) _ = panic "dsDo TransStmt"
937
938 handle_failure :: LPat Id -> MatchResult -> SyntaxExpr Id -> DsM CoreExpr
939 -- In a do expression, pattern-match failure just calls
940 -- the monadic 'fail' rather than throwing an exception
941 handle_failure pat match fail_op
942 | matchCanFail match
943 = do { fail_op' <- dsExpr fail_op
944 ; dflags <- getDynFlags
945 ; fail_msg <- mkStringExpr (mk_fail_msg dflags pat)
946 ; extractMatchResult match (App fail_op' fail_msg) }
947 | otherwise
948 = extractMatchResult match (error "It can't fail")
949
950 mk_fail_msg :: DynFlags -> Located e -> String
951 mk_fail_msg dflags pat = "Pattern match failure in do expression at " ++
952 showPpr dflags (getLoc pat)
953
954 {-
955 ************************************************************************
956 * *
957 \subsection{Errors and contexts}
958 * *
959 ************************************************************************
960 -}
961
962 -- Warn about certain types of values discarded in monadic bindings (#3263)
963 warnDiscardedDoBindings :: LHsExpr Id -> Type -> DsM ()
964 warnDiscardedDoBindings rhs rhs_ty
965 | Just (m_ty, elt_ty) <- tcSplitAppTy_maybe rhs_ty
966 = do { warn_unused <- woptM Opt_WarnUnusedDoBind
967 ; warn_wrong <- woptM Opt_WarnWrongDoBind
968 ; when (warn_unused || warn_wrong) $
969 do { fam_inst_envs <- dsGetFamInstEnvs
970 ; let norm_elt_ty = topNormaliseType fam_inst_envs elt_ty
971
972 -- Warn about discarding non-() things in 'monadic' binding
973 ; if warn_unused && not (isUnitTy norm_elt_ty)
974 then warnDs (badMonadBind rhs elt_ty
975 (ptext (sLit "-fno-warn-unused-do-bind")))
976 else
977
978 -- Warn about discarding m a things in 'monadic' binding of the same type,
979 -- but only if we didn't already warn due to Opt_WarnUnusedDoBind
980 when warn_wrong $
981 do { case tcSplitAppTy_maybe norm_elt_ty of
982 Just (elt_m_ty, _)
983 | m_ty `eqType` topNormaliseType fam_inst_envs elt_m_ty
984 -> warnDs (badMonadBind rhs elt_ty
985 (ptext (sLit "-fno-warn-wrong-do-bind")))
986 _ -> return () } } }
987
988 | otherwise -- RHS does have type of form (m ty), which is weird
989 = return () -- but at lesat this warning is irrelevant
990
991 badMonadBind :: LHsExpr Id -> Type -> SDoc -> SDoc
992 badMonadBind rhs elt_ty flag_doc
993 = vcat [ hang (ptext (sLit "A do-notation statement discarded a result of type"))
994 2 (quotes (ppr elt_ty))
995 , hang (ptext (sLit "Suppress this warning by saying"))
996 2 (quotes $ ptext (sLit "_ <-") <+> ppr rhs)
997 , ptext (sLit "or by using the flag") <+> flag_doc ]
998
999 {-
1000 ************************************************************************
1001 * *
1002 \subsection{Static pointers}
1003 * *
1004 ************************************************************************
1005 -}
1006
1007 -- | Creates an name for an entry in the Static Pointer Table.
1008 --
1009 -- The name has the form @sptEntry:<N>@ where @<N>@ is generated from a
1010 -- per-module counter.
1011 --
1012 mkSptEntryName :: SrcSpan -> DsM Name
1013 mkSptEntryName loc = do
1014 mod <- getModule
1015 occ <- mkWrapperName "sptEntry"
1016 newGlobalBinder mod occ loc
1017 where
1018 mkWrapperName what
1019 = do dflags <- getDynFlags
1020 thisMod <- getModule
1021 let -- Note [Generating fresh names for ccall wrapper]
1022 -- in compiler/typecheck/TcEnv.hs
1023 wrapperRef = nextWrapperNum dflags
1024 wrapperNum <- liftIO $ atomicModifyIORef' wrapperRef $ \mod_env ->
1025 let num = lookupWithDefaultModuleEnv mod_env 0 thisMod
1026 in (extendModuleEnv mod_env thisMod (num+1), num)
1027 return $ mkVarOcc $ what ++ ":" ++ show wrapperNum