ab9f8c7c26afe437a282d2c1f25ceac6ee0dfbda
[ghc-hetmet.git] / compiler / deSugar / Desugar.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 The Desugarer: turning HsSyn into Core.
7
8 \begin{code}
9 module Desugar ( deSugar, deSugarExpr ) where
10
11 import DynFlags
12 import StaticFlags
13 import HscTypes
14 import HsSyn
15 import TcRnTypes
16 import MkIface
17 import Id
18 import Name
19 import CoreSyn
20 import OccurAnal
21 import PprCore
22 import DsMonad
23 import DsExpr
24 import DsBinds
25 import DsForeign
26 import DsExpr           ()      -- Forces DsExpr to be compiled; DsBinds only
27                                 -- depends on DsExpr.hi-boot.
28 import Module
29 import RdrName
30 import NameSet
31 import VarSet
32 import Rules
33 import CoreLint
34 import CoreFVs
35 import ErrUtils
36 import Outputable
37 import SrcLoc
38 import Maybes
39 import FastString
40 import Coverage
41
42 import Data.IORef
43 \end{code}
44
45 %************************************************************************
46 %*                                                                      *
47 %*              The main function: deSugar
48 %*                                                                      *
49 %************************************************************************
50
51 \begin{code}
52 deSugar :: HscEnv -> ModLocation -> TcGblEnv -> IO (Messages, Maybe ModGuts)
53 -- Can modify PCS by faulting in more declarations
54
55 deSugar hsc_env 
56         mod_loc
57         tcg_env@(TcGblEnv { tcg_mod          = mod,
58                             tcg_src          = hsc_src,
59                             tcg_type_env     = type_env,
60                             tcg_imports      = imports,
61                             tcg_exports      = exports,
62                             tcg_keep         = keep_var,
63                             tcg_rdr_env      = rdr_env,
64                             tcg_fix_env      = fix_env,
65                             tcg_inst_env     = inst_env,
66                             tcg_fam_inst_env = fam_inst_env,
67                             tcg_warns      = warns,
68                             tcg_binds        = binds,
69                             tcg_fords        = fords,
70                             tcg_rules        = rules,
71                             tcg_insts        = insts,
72                             tcg_fam_insts    = fam_insts,
73                             tcg_hpc          = other_hpc_info })
74
75   = do  { let dflags = hsc_dflags hsc_env
76         ; showPass dflags "Desugar"
77
78         -- Desugar the program
79         ; let export_set = availsToNameSet exports
80         ; let auto_scc = mkAutoScc mod export_set
81         ; let target = hscTarget dflags
82         ; let hpcInfo = emptyHpcInfo other_hpc_info
83         ; (msgs, mb_res)
84               <- case target of
85                    HscNothing ->
86                        return (emptyMessages,
87                                Just ([], [], NoStubs, hpcInfo, emptyModBreaks))
88                    _        -> do
89                      (binds_cvr,ds_hpc_info, modBreaks)
90                          <- if (opt_Hpc
91                                   || target == HscInterpreted)
92                                && (not (isHsBoot hsc_src))
93                               then addCoverageTicksToBinds dflags mod mod_loc (typeEnvTyCons type_env) binds 
94                               else return (binds, hpcInfo, emptyModBreaks)
95                      initDs hsc_env mod rdr_env type_env $ do
96                          core_prs <- dsTopLHsBinds auto_scc binds_cvr
97                          (ds_fords, foreign_prs) <- dsForeigns fords
98                          let all_prs = foreign_prs ++ core_prs
99                          ds_rules <- mapM dsRule rules
100                          return (all_prs, catMaybes ds_rules, ds_fords, ds_hpc_info, modBreaks)
101
102         ; case mb_res of {
103            Nothing -> return (msgs, Nothing) ;
104            Just (all_prs, ds_rules, ds_fords,ds_hpc_info, modBreaks) -> do
105
106         {       -- Add export flags to bindings
107           keep_alive <- readIORef keep_var
108         ; let final_prs = addExportFlags target export_set
109                                  keep_alive all_prs ds_rules
110               ds_binds  = [Rec final_prs]
111         -- Notice that we put the whole lot in a big Rec, even the foreign binds
112         -- When compiling PrelFloat, which defines data Float = F# Float#
113         -- we want F# to be in scope in the foreign marshalling code!
114         -- You might think it doesn't matter, but the simplifier brings all top-level
115         -- things into the in-scope set before simplifying; so we get no unfolding for F#!
116
117         -- Lint result if necessary
118         ; endPass dflags "Desugar" Opt_D_dump_ds ds_binds
119
120         -- Dump output
121         ; doIfSet (dopt Opt_D_dump_ds dflags) 
122                   (printDump (ppr_ds_rules ds_rules))
123
124         ; used_names <- mkUsedNames tcg_env
125         ; deps <- mkDependencies tcg_env
126
127         ; let mod_guts = ModGuts {      
128                 mg_module       = mod,
129                 mg_boot         = isHsBoot hsc_src,
130                 mg_exports      = exports,
131                 mg_deps         = deps,
132                 mg_used_names   = used_names,
133                 mg_dir_imps     = imp_mods imports,
134                 mg_rdr_env      = rdr_env,
135                 mg_fix_env      = fix_env,
136                 mg_warns        = warns,
137                 mg_types        = type_env,
138                 mg_insts        = insts,
139                 mg_fam_insts    = fam_insts,
140                 mg_inst_env     = inst_env,
141                 mg_fam_inst_env = fam_inst_env,
142                 mg_rules        = ds_rules,
143                 mg_binds        = ds_binds,
144                 mg_foreign      = ds_fords,
145                 mg_hpc_info     = ds_hpc_info,
146                 mg_modBreaks    = modBreaks,
147                 mg_vect_info    = noVectInfo
148               }
149         ; return (msgs, Just mod_guts)
150         }}}
151
152 mkAutoScc :: Module -> NameSet -> AutoScc
153 mkAutoScc mod exports
154   | not opt_SccProfilingOn      -- No profiling
155   = NoSccs              
156   | opt_AutoSccsOnAllToplevs    -- Add auto-scc on all top-level things
157   = AddSccs mod (\id -> not $ isDerivedOccName $ getOccName id)
158     -- See #1641.  This is pretty yucky, but I can't see a better way
159     -- to identify compiler-generated Ids, and at least this should
160     -- catch them all.
161   | opt_AutoSccsOnExportedToplevs       -- Only on exported things
162   = AddSccs mod (\id -> idName id `elemNameSet` exports)
163   | otherwise
164   = NoSccs
165
166 deSugarExpr :: HscEnv
167             -> Module -> GlobalRdrEnv -> TypeEnv 
168             -> LHsExpr Id
169             -> IO (Messages, Maybe CoreExpr)
170 -- Prints its own errors; returns Nothing if error occurred
171
172 deSugarExpr hsc_env this_mod rdr_env type_env tc_expr = do
173     let dflags = hsc_dflags hsc_env
174     showPass dflags "Desugar"
175
176     -- Do desugaring
177     (msgs, mb_core_expr) <- initDs hsc_env this_mod rdr_env type_env $
178                                    dsLExpr tc_expr
179
180     case mb_core_expr of
181       Nothing   -> return (msgs, Nothing)
182       Just expr -> do
183
184         -- Dump output
185         dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr expr)
186
187         return (msgs, Just expr)
188
189 --              addExportFlags
190 -- Set the no-discard flag if either 
191 --      a) the Id is exported
192 --      b) it's mentioned in the RHS of an orphan rule
193 --      c) it's in the keep-alive set
194 --
195 -- It means that the binding won't be discarded EVEN if the binding
196 -- ends up being trivial (v = w) -- the simplifier would usually just 
197 -- substitute w for v throughout, but we don't apply the substitution to
198 -- the rules (maybe we should?), so this substitution would make the rule
199 -- bogus.
200
201 -- You might wonder why exported Ids aren't already marked as such;
202 -- it's just because the type checker is rather busy already and
203 -- I didn't want to pass in yet another mapping.
204
205 addExportFlags :: HscTarget -> NameSet -> NameSet -> [(Id, t)] -> [CoreRule]
206                -> [(Id, t)]
207 addExportFlags target exports keep_alive prs rules
208   = [(add_export bndr, rhs) | (bndr,rhs) <- prs]
209   where
210     add_export bndr
211         | dont_discard bndr = setIdExported bndr
212         | otherwise         = bndr
213
214     orph_rhs_fvs = unionVarSets [ ruleRhsFreeVars rule
215                                 | rule <- rules, 
216                                   not (isLocalRule rule) ]
217         -- A non-local rule keeps alive the free vars of its right-hand side. 
218         -- (A "non-local" is one whose head function is not locally defined.)
219         -- Local rules are (later, after gentle simplification) 
220         -- attached to the Id, and that keeps the rhs free vars alive.
221
222     dont_discard bndr = is_exported name
223                      || name `elemNameSet` keep_alive
224                      || bndr `elemVarSet` orph_rhs_fvs 
225                      where
226                         name = idName bndr
227
228         -- In interactive mode, we don't want to discard any top-level
229         -- entities at all (eg. do not inline them away during
230         -- simplification), and retain them all in the TypeEnv so they are
231         -- available from the command line.
232         --
233         -- isExternalName separates the user-defined top-level names from those
234         -- introduced by the type checker.
235     is_exported :: Name -> Bool
236     is_exported | target == HscInterpreted = isExternalName
237                 | otherwise                = (`elemNameSet` exports)
238
239 ppr_ds_rules :: [CoreRule] -> SDoc
240 ppr_ds_rules [] = empty
241 ppr_ds_rules rules
242   = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
243     pprRules rules
244 \end{code}
245
246
247
248 %************************************************************************
249 %*                                                                      *
250 %*              Desugaring transformation rules
251 %*                                                                      *
252 %************************************************************************
253
254 \begin{code}
255 dsRule :: LRuleDecl Id -> DsM (Maybe CoreRule)
256 dsRule (L loc (HsRule name act vars lhs _tv_lhs rhs _fv_rhs))
257   = putSrcSpanDs loc $ 
258     do  { let bndrs = [var | RuleBndr (L _ var) <- vars]
259         ; lhs'  <- dsLExpr lhs
260         ; rhs'  <- dsLExpr rhs
261
262         ; case decomposeRuleLhs (occurAnalyseExpr lhs') of {
263                 Nothing -> do { warnDs msg; return Nothing } ;
264                 Just (fn_id, args) -> do
265         
266         -- Substitute the dict bindings eagerly,
267         -- and take the body apart into a (f args) form
268         { let local_rule = isLocalId fn_id
269                 -- NB: isLocalId is False of implicit Ids.  This is good becuase
270                 -- we don't want to attach rules to the bindings of implicit Ids, 
271                 -- because they don't show up in the bindings until just before code gen
272               fn_name   = idName fn_id
273
274               rule = Rule { ru_name = name, ru_fn = fn_name, ru_act = act,
275                             ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs', 
276                             ru_rough = roughTopNames args, 
277                             ru_local = local_rule }
278         ; return (Just rule)
279         } } }
280   where
281     msg = hang (ptext (sLit "RULE left-hand side too complicated to desugar; ignored"))
282              2 (ppr lhs)
283 \end{code}