[project @ 1999-03-25 13:13:51 by simonm]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsBinds.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[DsBinds]{Pattern-matching bindings (HsBinds and MonoBinds)}
5
6 Handles @HsBinds@; those at the top level require different handling,
7 in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at
8 lower levels it is preserved with @let@/@letrec@s).
9
10 \begin{code}
11 module DsBinds ( dsMonoBinds, AutoScc(..) ) where
12
13 #include "HsVersions.h"
14
15
16 import {-# SOURCE #-}   DsExpr( dsExpr )
17
18 import HsSyn            -- lots of things
19 import CoreSyn          -- lots of things
20 import CoreUtils        ( coreExprType )
21 import TcHsSyn          ( TypecheckedMonoBinds )
22 import DsMonad
23 import DsGRHSs          ( dsGuarded )
24 import DsUtils
25 import Match            ( matchWrapper )
26
27 import BasicTypes       ( RecFlag(..) )
28 import CmdLineOpts      ( opt_SccProfilingOn, opt_AutoSccsOnAllToplevs, 
29                           opt_AutoSccsOnExportedToplevs, opt_AutoSccsOnDicts
30                         )
31 import CostCentre       ( CostCentre, mkAutoCC, IsCafCC(..) )
32 import Id               ( idType, Id )
33 import VarEnv
34 import Name             ( isExported )
35 import Type             ( mkTyVarTy, isDictTy, substTy )
36 import TysWiredIn       ( voidTy )
37 import Outputable
38
39 import Maybe
40 import IOExts (trace)
41 \end{code}
42
43 %************************************************************************
44 %*                                                                      *
45 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
46 %*                                                                      *
47 %************************************************************************
48
49 \begin{code}
50 dsMonoBinds :: AutoScc                  -- scc annotation policy (see below)
51             -> TypecheckedMonoBinds
52             -> [(Id,CoreExpr)]          -- Put this on the end (avoid quadratic append)
53             -> DsM [(Id,CoreExpr)]      -- Result
54
55 dsMonoBinds _ EmptyMonoBinds rest = returnDs rest
56
57 dsMonoBinds auto_scc (AndMonoBinds  binds_1 binds_2) rest
58   = dsMonoBinds auto_scc binds_2 rest   `thenDs` \ rest' ->
59     dsMonoBinds auto_scc binds_1 rest'
60
61 dsMonoBinds _ (CoreMonoBind var core_expr) rest
62   = returnDs ((var, core_expr) : rest)
63
64 dsMonoBinds _ (VarMonoBind var expr) rest
65   = dsExpr expr                 `thenDs` \ core_expr ->
66
67         -- Dictionary bindings are always VarMonoBinds, so
68         -- we only need do this here
69     addDictScc var core_expr    `thenDs` \ core_expr' ->
70
71     returnDs ((var, core_expr') : rest)
72
73 dsMonoBinds auto_scc (FunMonoBind fun _ matches locn) rest
74   = putSrcLocDs locn    $
75     matchWrapper (FunMatch fun) matches error_string    `thenDs` \ (args, body) ->
76     addAutoScc auto_scc (fun, mkLams args body)         `thenDs` \ pair ->
77     returnDs (pair : rest)
78   where
79     error_string = "function " ++ showSDoc (ppr fun)
80
81 dsMonoBinds auto_scc (PatMonoBind pat grhss locn) rest
82   = putSrcLocDs locn $
83     dsGuarded grhss                             `thenDs` \ body_expr ->
84     mkSelectorBinds pat body_expr               `thenDs` \ sel_binds ->
85     mapDs (addAutoScc auto_scc) sel_binds       `thenDs` \ sel_binds ->
86     returnDs (sel_binds ++ rest)
87
88         -- Common case: one exported variable
89         -- All non-recursive bindings come through this way
90 dsMonoBinds auto_scc (AbsBinds all_tyvars dicts exps@[(tyvars, global, local)] binds) rest
91   = ASSERT( all (`elem` tyvars) all_tyvars )
92     dsMonoBinds (addSccs auto_scc exps) binds []        `thenDs` \ core_prs ->
93     let 
94         -- Always treat the binds as recursive, because the typechecker
95         -- makes rather mixed-up dictionary bindings
96         core_binds = [Rec core_prs]
97         global' = (global, mkLams tyvars $ mkLams dicts $ 
98                            mkLets core_binds (Var local))
99     in
100     
101     returnDs (global' : rest)
102
103         -- Another Common special case: no type or dictionary abstraction
104 dsMonoBinds auto_scc (AbsBinds [] [] exports binds) rest
105   = let exports' = [(global, Var local) | (_, global, local) <- exports] in
106     dsMonoBinds (addSccs auto_scc exports) binds (exports' ++ rest)
107
108 dsMonoBinds auto_scc (AbsBinds all_tyvars dicts exports binds) rest
109   = dsMonoBinds (addSccs auto_scc exports) binds []`thenDs` \ core_prs ->
110     let 
111         core_binds = [Rec core_prs]
112
113         tup_expr      = mkTupleExpr locals
114         tup_ty        = coreExprType tup_expr
115         poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
116                         mkLets core_binds tup_expr
117         locals        = [local | (_, _, local) <- exports]
118         local_tys     = map idType locals
119     in
120     newSysLocalDs (coreExprType poly_tup_expr)          `thenDs` \ poly_tup_id ->
121     let
122         dict_args = map Var dicts
123
124         mk_bind (tyvars, global, local) n       -- locals !! n == local
125           =     -- Need to make fresh locals to bind in the selector, because
126                 -- some of the tyvars will be bound to voidTy
127             newSysLocalsDs (map (substTy env) local_tys)        `thenDs` \ locals' ->
128             newSysLocalDs  (substTy env tup_ty)                 `thenDs` \ tup_id ->
129             returnDs (global, mkLams tyvars $ mkLams dicts $
130                               mkTupleSelector locals' (locals' !! n) tup_id $
131                               mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args)
132           where
133             mk_ty_arg all_tyvar | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
134                                 | otherwise               = voidTy
135             ty_args = map mk_ty_arg all_tyvars
136             env     = all_tyvars `zipVarEnv` ty_args
137     in
138     zipWithDs mk_bind exports [0..]             `thenDs` \ export_binds ->
139      -- don't scc (auto-)annotate the tuple itself.
140     returnDs ((poly_tup_id, poly_tup_expr) : (export_binds ++ rest))
141 \end{code}
142
143
144 %************************************************************************
145 %*                                                                      *
146 \subsection[addAutoScc]{Adding automatic sccs}
147 %*                                                                      *
148 %************************************************************************
149
150 \begin{code}
151 data AutoScc
152         = TopLevel
153         | TopLevelAddSccs (Id -> Maybe Id)
154         | NoSccs
155
156 addSccs :: AutoScc -> [(a,Id,Id)] -> AutoScc
157 addSccs auto_scc@(TopLevelAddSccs _) exports = auto_scc
158 addSccs NoSccs   exports = NoSccs
159 addSccs TopLevel exports 
160   = TopLevelAddSccs (\id -> case [ exp | (_,exp,loc) <- exports, loc == id ] of
161                                 (exp:_)  | opt_AutoSccsOnAllToplevs || 
162                                             (isExported exp && 
163                                              opt_AutoSccsOnExportedToplevs)
164                                         -> Just exp
165                                 _ -> Nothing)
166
167 addAutoScc :: AutoScc           -- if needs be, decorate toplevs?
168            -> (Id, CoreExpr)
169            -> DsM (Id, CoreExpr)
170
171 addAutoScc (TopLevelAddSccs auto_scc_fn) pair@(bndr, core_expr) 
172  | do_auto_scc && worthSCC core_expr
173      = getModuleAndGroupDs `thenDs` \ (mod,grp) ->
174        returnDs (bndr, Note (SCC (mkAutoCC top_bndr mod grp NotCafCC)) core_expr)
175  where do_auto_scc = isJust maybe_auto_scc
176        maybe_auto_scc = auto_scc_fn bndr
177        (Just top_bndr) = maybe_auto_scc
178 addAutoScc _ pair
179      = returnDs pair
180
181 worthSCC (Note (SCC _) _) = False
182 worthSCC (Con _ _)        = False
183 worthSCC core_expr        = True
184 \end{code}
185
186 If profiling and dealing with a dict binding, wrap the dict in "_scc_ DICT <dict>":
187
188 \begin{code}
189 addDictScc var rhs = returnDs rhs
190
191 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
192   | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
193     || not (isDictTy (idType var))
194   = returnDs rhs                                -- That's easy: do nothing
195
196   | otherwise
197   = getModuleAndGroupDs         `thenDs` \ (mod, grp) ->
198         -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
199     returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
200 -}
201 \end{code}