Monadify deSugar/DsBinds: use do, return, applicative, standard monad functions
[ghc-hetmet.git] / compiler / deSugar / DsBinds.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Pattern-matching bindings (HsBinds and MonoBinds)
7
8 Handles @HsBinds@; those at the top level require different handling,
9 in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at
10 lower levels it is preserved with @let@/@letrec@s).
11
12 \begin{code}
13 {-# OPTIONS -w #-}
14 -- The above warning supression flag is a temporary kludge.
15 -- While working on this module you are encouraged to remove it and fix
16 -- any warnings in the module. See
17 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
18 -- for details
19
20 module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs, 
21                  dsCoercion,
22                  AutoScc(..)
23   ) where
24
25 #include "HsVersions.h"
26
27 import {-# SOURCE #-}   DsExpr( dsLExpr, dsExpr )
28 import {-# SOURCE #-}   Match( matchWrapper )
29
30 import DsMonad
31 import DsGRHSs
32 import DsUtils
33
34 import HsSyn            -- lots of things
35 import CoreSyn          -- lots of things
36 import CoreUtils
37 import CoreFVs
38
39 import TcHsSyn          ( mkArbitraryType )     -- Mis-placed?
40 import TcType
41 import OccurAnal
42 import CostCentre
43 import Module
44 import Id
45 import Var      ( TyVar )
46 import VarSet
47 import Rules
48 import VarEnv
49 import Type
50 import Outputable
51 import SrcLoc
52 import Maybes
53 import Bag
54 import BasicTypes hiding ( TopLevel )
55 import FastString
56 import Util             ( mapSnd )
57
58 import Control.Monad
59 import Data.List
60 \end{code}
61
62 %************************************************************************
63 %*                                                                      *
64 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
65 %*                                                                      *
66 %************************************************************************
67
68 \begin{code}
69 dsTopLHsBinds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
70 dsTopLHsBinds auto_scc binds = ds_lhs_binds auto_scc binds
71
72 dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
73 dsLHsBinds binds = ds_lhs_binds NoSccs binds
74
75
76 ------------------------
77 ds_lhs_binds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
78          -- scc annotation policy (see below)
79 ds_lhs_binds auto_scc binds =  foldM (dsLHsBind auto_scc) [] (bagToList binds)
80
81 dsLHsBind :: AutoScc
82          -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
83          -> LHsBind Id
84          -> DsM [(Id,CoreExpr)] -- Result
85 dsLHsBind auto_scc rest (L loc bind)
86   = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
87
88 dsHsBind :: AutoScc
89          -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
90          -> HsBind Id
91          -> DsM [(Id,CoreExpr)] -- Result
92
93 dsHsBind auto_scc rest (VarBind var expr) = do
94     core_expr <- dsLExpr expr
95
96         -- Dictionary bindings are always VarMonoBinds, so
97         -- we only need do this here
98     core_expr' <- addDictScc var core_expr
99     return ((var, core_expr') : rest)
100
101 dsHsBind auto_scc rest (FunBind { fun_id = L _ fun, fun_matches = matches, 
102                                   fun_co_fn = co_fn, fun_tick = tick, fun_infix = inf }) = do
103     (args, body) <- matchWrapper (FunRhs (idName fun) inf) matches
104     body' <- mkOptTickBox tick body
105     rhs <- dsCoercion co_fn (return (mkLams args body'))
106     return ((fun,rhs) : rest)
107
108 dsHsBind auto_scc rest (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty }) = do
109     body_expr <- dsGuarded grhss ty
110     sel_binds <- mkSelectorBinds pat body_expr
111     return (sel_binds ++ rest)
112
113 -- Note [Rules and inlining]
114 -- Common special case: no type or dictionary abstraction
115 -- This is a bit less trivial than you might suppose
116 -- The naive way woudl be to desguar to something like
117 --      f_lcl = ...f_lcl...     -- The "binds" from AbsBinds
118 --      M.f = f_lcl             -- Generated from "exports"
119 -- But we don't want that, because if M.f isn't exported,
120 -- it'll be inlined unconditionally at every call site (its rhs is 
121 -- trivial).  That would be ok unless it has RULES, which would 
122 -- thereby be completely lost.  Bad, bad, bad.
123 --
124 -- Instead we want to generate
125 --      M.f = ...f_lcl...
126 --      f_lcl = M.f
127 -- Now all is cool. The RULES are attached to M.f (by SimplCore), 
128 -- and f_lcl is rapidly inlined away.
129 --
130 -- This does not happen in the same way to polymorphic binds,
131 -- because they desugar to
132 --      M.f = /\a. let f_lcl = ...f_lcl... in f_lcl
133 -- Although I'm a bit worried about whether full laziness might
134 -- float the f_lcl binding out and then inline M.f at its call site
135
136 dsHsBind auto_scc rest (AbsBinds [] [] exports binds)
137   = do  { core_prs <- ds_lhs_binds NoSccs binds
138         ; let env = mkABEnv exports
139               do_one (lcl_id, rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
140                                    = addInlinePrags prags gbl_id $
141                                      addAutoScc auto_scc gbl_id rhs
142                                    | otherwise = (lcl_id, rhs)
143               locals'  = [(lcl_id, Var gbl_id) | (_, gbl_id, lcl_id, _) <- exports]
144         ; return (map do_one core_prs ++ locals' ++ rest) }
145                 -- No Rec needed here (contrast the other AbsBinds cases)
146                 -- because we can rely on the enclosing dsBind to wrap in Rec
147
148         -- Another common case: one exported variable
149         -- Non-recursive bindings come through this way
150 dsHsBind auto_scc rest
151      (AbsBinds all_tyvars dicts exports@[(tyvars, global, local, prags)] binds)
152   = ASSERT( all (`elem` tyvars) all_tyvars ) do
153     core_prs <- ds_lhs_binds NoSccs binds
154     let
155         -- Always treat the binds as recursive, because the typechecker
156         -- makes rather mixed-up dictionary bindings
157         core_bind = Rec core_prs
158     
159     mb_specs <- mapM (dsSpec all_tyvars dicts tyvars global local core_bind) prags
160     let
161         (spec_binds, rules) = unzip (catMaybes mb_specs)
162         global' = addIdSpecialisations global rules
163         rhs'    = mkLams tyvars $ mkLams dicts $ Let core_bind (Var local)
164         bind    = addInlinePrags prags global' $ addAutoScc auto_scc global' rhs'
165     
166     return (bind  : spec_binds ++ rest)
167
168 dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
169   = do  { core_prs <- ds_lhs_binds NoSccs binds
170         ; let env = mkABEnv exports
171               do_one (lcl_id,rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
172                                   = addInlinePrags prags lcl_id $
173                                     addAutoScc auto_scc gbl_id rhs
174                                   | otherwise = (lcl_id,rhs)
175                
176                 -- Rec because of mixed-up dictionary bindings
177               core_bind = Rec (map do_one core_prs)
178
179               tup_expr      = mkBigCoreVarTup locals
180               tup_ty        = exprType tup_expr
181               poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
182                               Let core_bind tup_expr
183               locals        = [local | (_, _, local, _) <- exports]
184               local_tys     = map idType locals
185
186         ; poly_tup_id <- newSysLocalDs (exprType poly_tup_expr)
187
188         ; let dict_args = map Var dicts
189
190               mk_bind ((tyvars, global, local, prags), n)       -- locals !! n == local
191                 =       -- Need to make fresh locals to bind in the selector, because
192                         -- some of the tyvars will be bound to 'Any'
193                   do { ty_args <- mapM mk_ty_arg all_tyvars
194                      ; let substitute = substTyWith all_tyvars ty_args
195                      ; locals' <- newSysLocalsDs (map substitute local_tys)
196                      ; tup_id  <- newSysLocalDs  (substitute tup_ty)
197                      ; mb_specs <- mapM (dsSpec all_tyvars dicts tyvars global local core_bind) 
198                                          prags
199                      ; let (spec_binds, rules) = unzip (catMaybes mb_specs)
200                            global' = addIdSpecialisations global rules
201                            rhs = mkLams tyvars $ mkLams dicts $
202                                  mkTupleSelector locals' (locals' !! n) tup_id $
203                                  mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args
204                      ; return ((global', rhs) : spec_binds) }
205                 where
206                   mk_ty_arg all_tyvar
207                         | all_tyvar `elem` tyvars = return (mkTyVarTy all_tyvar)
208                         | otherwise               = dsMkArbitraryType all_tyvar
209
210         ; export_binds_s <- mapM mk_bind (exports `zip` [0..])
211              -- don't scc (auto-)annotate the tuple itself.
212
213         ; return ((poly_tup_id, poly_tup_expr) : 
214                     (concat export_binds_s ++ rest)) }
215
216 mkABEnv :: [([TyVar], Id, Id, [LPrag])] -> VarEnv (Id, [LPrag])
217 -- Takes the exports of a AbsBinds, and returns a mapping
218 --      lcl_id -> (gbl_id, prags)
219 mkABEnv exports = mkVarEnv [ (lcl_id, (gbl_id, prags)) 
220                            | (_, gbl_id, lcl_id, prags) <- exports]
221
222
223 dsSpec :: [TyVar] -> [DictId] -> [TyVar]
224        -> Id -> Id              -- Global, local
225        -> CoreBind -> LPrag
226        -> DsM (Maybe ((Id,CoreExpr),    -- Binding for specialised Id
227                       CoreRule))        -- Rule for the Global Id
228
229 -- Example:
230 --      f :: (Eq a, Ix b) => a -> b -> b
231 --      {-# SPECIALISE f :: Ix b => Int -> b -> b #-}
232 --
233 --      AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
234 -- 
235 --      SpecPrag (/\b.\(d:Ix b). f Int b dInt d) 
236 --               (forall b. Ix b => Int -> b -> b)
237 --
238 -- Rule:        forall b,(d:Ix b). f Int b dInt d = f_spec b d
239 --
240 -- Spec bind:   f_spec = Let f = /\ab \(d1:Eq a)(d2:Ix b). let binds in f_mono 
241 --                       /\b.\(d:Ix b). in f Int b dInt d
242 --              The idea is that f occurs just once, so it'll be 
243 --              inlined and specialised
244 --
245 -- Given SpecPrag (/\as.\ds. f es) t, we have
246 -- the defn             f_spec as ds = let-nonrec f = /\fas\fds. let f_mono = <f-rhs> in f_mono
247 --                                     in f es 
248 -- and the RULE         forall as, ds. f es = f_spec as ds
249 --
250 -- It is *possible* that 'es' does not mention all of the dictionaries 'ds'
251 -- (a bit silly, because then the 
252 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (L _ (InlinePrag {}))
253   = return Nothing
254
255 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
256        (L loc (SpecPrag spec_expr spec_ty inl))
257   = putSrcSpanDs loc $ 
258     do  { let poly_name = idName poly_id
259         ; spec_name <- newLocalName poly_name
260         ; ds_spec_expr  <- dsExpr spec_expr
261         ; let (bndrs, body) = collectBinders (occurAnalyseExpr ds_spec_expr)
262                 -- The occurrence-analysis does two things
263                 -- (a) identifies unused binders: Note [Unused spec binders]
264                 -- (b) sorts dict bindings into NonRecs 
265                 --      so they can be inlined by decomposeRuleLhs
266               mb_lhs = decomposeRuleLhs body
267
268         -- Check for dead binders: Note [Unused spec binders]
269         ; case filter isDeadBinder bndrs of {
270                 bs | not (null bs) -> do { warnDs (dead_msg bs); return Nothing }
271                    | otherwise -> 
272
273           case mb_lhs of
274             Nothing -> do { warnDs decomp_msg; return Nothing }
275
276             Just (var, args) -> do
277         
278         { f_body <- fix_up (Let mono_bind (Var mono_id))
279
280         ; let     local_poly  = setIdNotExported poly_id
281                         -- Very important to make the 'f' non-exported,
282                         -- else it won't be inlined!
283                   spec_id     = mkLocalId spec_name spec_ty
284                   spec_rhs    = Let (NonRec local_poly poly_f_body) ds_spec_expr
285                   poly_f_body = mkLams (tvs ++ dicts) f_body
286                                 
287                   extra_dict_bndrs = filter isDictId (varSetElems (exprFreeVars ds_spec_expr))
288                         -- Note [Const rule dicts]
289
290                   rule =  mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
291                                 AlwaysActive poly_name
292                                 (extra_dict_bndrs ++ bndrs) args
293                                 (mkVarApps (Var spec_id) bndrs)
294         ; return (Just (addInlineInfo inl spec_id spec_rhs, rule))
295         } } }
296   where
297         -- Bind to Any any of all_ptvs that aren't 
298         -- relevant for this particular function 
299     fix_up body | null void_tvs = return body
300                 | otherwise     = do { void_tys <- mapM dsMkArbitraryType void_tvs
301                                      ; return (mkTyApps (mkLams void_tvs body) void_tys) }
302
303     void_tvs = all_tvs \\ tvs
304
305     dead_msg bs = vcat [ sep [ptext SLIT("Useless constraint") <> plural bs
306                                  <+> ptext SLIT("in specialied type:"),
307                              nest 2 (pprTheta (map get_pred bs))]
308                        , ptext SLIT("SPECIALISE pragma ignored")]
309     get_pred b = ASSERT( isId b ) expectJust "dsSpec" (tcSplitPredTy_maybe (idType b))
310
311     decomp_msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
312                     2 (ppr spec_expr)
313
314 dsMkArbitraryType tv = mkArbitraryType warn tv
315   where
316     warn span msg = putSrcSpanDs span (warnDs msg)
317 \end{code}
318
319 Note [Unused spec binders]
320 ~~~~~~~~~~~~~~~~~~~~~~~~~~
321 Consider
322         f :: a -> a
323         {-# SPECIALISE f :: Eq a => a -> a #-}
324 It's true that this *is* a more specialised type, but the rule
325 we get is something like this:
326         f_spec d = f
327         RULE: f = f_spec d
328 Note that the rule is bogus, becuase it mentions a 'd' that is
329 not bound on the LHS!  But it's a silly specialisation anyway, becuase
330 the constraint is unused.  We could bind 'd' to (error "unused")
331 but it seems better to reject the program because it's almost certainly
332 a mistake.  That's what the isDeadBinder call detects.
333
334 Note [Const rule dicts]
335 ~~~~~~~~~~~~~~~~~~~~~~~
336 When the LHS of a specialisation rule, (/\as\ds. f es) has a free dict, 
337 which is presumably in scope at the function definition site, we can quantify 
338 over it too.  *Any* dict with that type will do.
339
340 So for example when you have
341         f :: Eq a => a -> a
342         f = <rhs>
343         {-# SPECIALISE f :: Int -> Int #-}
344
345 Then we get the SpecPrag
346         SpecPrag (f Int dInt) Int
347
348 And from that we want the rule
349         
350         RULE forall dInt. f Int dInt = f_spec
351         f_spec = let f = <rhs> in f Int dInt
352
353
354
355 %************************************************************************
356 %*                                                                      *
357 \subsection{Adding inline pragmas}
358 %*                                                                      *
359 %************************************************************************
360
361 \begin{code}
362 decomposeRuleLhs :: CoreExpr -> Maybe (Id, [CoreExpr])
363 -- Returns Nothing if the LHS isn't of the expected shape
364 decomposeRuleLhs lhs 
365   = go emptyVarEnv (occurAnalyseExpr lhs)       -- Occurrence analysis sorts out the dict
366                                                 -- bindings so we know if they are recursive
367   where
368         -- Substitute dicts in the LHS args, so that there 
369         -- aren't any lets getting in the way
370         -- Note that we substitute the function too; we might have this as
371         -- a LHS:       let f71 = M.f Int in f71
372     go env (Let (NonRec dict rhs) body) 
373         = go (extendVarEnv env dict (simpleSubst env rhs)) body
374     go env body 
375         = case collectArgs (simpleSubst env body) of
376             (Var fn, args) -> Just (fn, args)
377             other          -> Nothing
378
379 simpleSubst :: IdEnv CoreExpr -> CoreExpr -> CoreExpr
380 -- Similar to CoreSubst.substExpr, except that 
381 -- (a) takes no account of capture; dictionary bindings use new names
382 -- (b) can have a GlobalId (imported) in its domain
383 -- (c) Ids only; no types are substituted
384 --
385 -- (b) is the reason we can't use CoreSubst... and it's no longer relevant
386 --      so really we should replace simpleSubst 
387 simpleSubst subst expr
388   = go expr
389   where
390     go (Var v)         = lookupVarEnv subst v `orElse` Var v
391     go (Cast e co)     = Cast (go e) co
392     go (Type ty)       = Type ty
393     go (Lit lit)       = Lit lit
394     go (App fun arg)   = App (go fun) (go arg)
395     go (Note note e)   = Note note (go e)
396     go (Lam bndr body) = Lam bndr (go body)
397     go (Let (NonRec bndr rhs) body) = Let (NonRec bndr (go rhs)) (go body)
398     go (Let (Rec pairs) body)       = Let (Rec (mapSnd go pairs)) (go body)
399     go (Case scrut bndr ty alts)    = Case (go scrut) bndr ty 
400                                            [(c,bs,go r) | (c,bs,r) <- alts]
401
402 addInlinePrags :: [LPrag] -> Id -> CoreExpr -> (Id,CoreExpr)
403 addInlinePrags prags bndr rhs
404   = case [inl | L _ (InlinePrag inl) <- prags] of
405         []      -> (bndr, rhs)
406         (inl:_) -> addInlineInfo inl bndr rhs
407
408 addInlineInfo :: InlineSpec -> Id -> CoreExpr -> (Id,CoreExpr)
409 addInlineInfo (Inline phase is_inline) bndr rhs
410   = (attach_phase bndr phase, wrap_inline is_inline rhs)
411   where
412     attach_phase bndr phase 
413         | isAlwaysActive phase = bndr   -- Default phase
414         | otherwise            = bndr `setInlinePragma` phase
415
416     wrap_inline True  body = mkInlineMe body
417     wrap_inline False body = body
418 \end{code}
419
420
421 %************************************************************************
422 %*                                                                      *
423 \subsection[addAutoScc]{Adding automatic sccs}
424 %*                                                                      *
425 %************************************************************************
426
427 \begin{code}
428 data AutoScc = NoSccs 
429              | AddSccs Module (Id -> Bool)
430 -- The (Id->Bool) says which Ids to add SCCs to 
431
432 addAutoScc :: AutoScc   
433            -> Id        -- Binder
434            -> CoreExpr  -- Rhs
435            -> CoreExpr  -- Scc'd Rhs
436
437 addAutoScc NoSccs _ rhs
438   = rhs
439 addAutoScc (AddSccs mod add_scc) id rhs
440   | add_scc id = mkSCC (mkAutoCC id mod NotCafCC) rhs
441   | otherwise  = rhs
442 \end{code}
443
444 If profiling and dealing with a dict binding,
445 wrap the dict in @_scc_ DICT <dict>@:
446
447 \begin{code}
448 addDictScc var rhs = return rhs
449
450 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
451   | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
452     || not (isDictId var)
453   = return rhs                          -- That's easy: do nothing
454
455   | otherwise
456   = do (mod, grp) <- getModuleAndGroupDs
457         -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
458        return (Note (SCC (mkAllDictsCC mod grp False)) rhs)
459 -}
460 \end{code}
461
462
463 %************************************************************************
464 %*                                                                      *
465                 Desugaring coercions
466 %*                                                                      *
467 %************************************************************************
468
469
470 \begin{code}
471 dsCoercion :: HsWrapper -> DsM CoreExpr -> DsM CoreExpr
472 dsCoercion WpHole            thing_inside = thing_inside
473 dsCoercion (WpCompose c1 c2) thing_inside = dsCoercion c1 (dsCoercion c2 thing_inside)
474 dsCoercion (WpCo co)     thing_inside = do { expr <- thing_inside
475                                                ; return (Cast expr co) }
476 dsCoercion (WpLam id)        thing_inside = do { expr <- thing_inside
477                                                ; return (Lam id expr) }
478 dsCoercion (WpTyLam tv)      thing_inside = do { expr <- thing_inside
479                                                ; return (Lam tv expr) }
480 dsCoercion (WpApp id)        thing_inside = do { expr <- thing_inside
481                                                ; return (App expr (Var id)) }
482 dsCoercion (WpTyApp ty)      thing_inside = do { expr <- thing_inside
483                                                ; return (App expr (Type ty)) }
484 dsCoercion WpInline          thing_inside = do { expr <- thing_inside
485                                                ; return (mkInlineMe expr) }
486 dsCoercion (WpLet bs)        thing_inside = do { prs <- dsLHsBinds bs
487                                                ; expr <- thing_inside
488                                                ; return (Let (Rec prs) expr) }
489 \end{code}