970bd2019db68a970440a93e569866461b6806a3
[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 #include "HsVersions.h"
12
13 import DynFlags
14 import StaticFlags
15 import HscTypes
16 import HsSyn
17 import TcRnTypes
18 import MkIface
19 import Id
20 import Name
21 import CoreSyn
22 import PprCore
23 import DsMonad
24 import DsExpr
25 import DsBinds
26 import DsForeign
27 import DsExpr           ()      -- Forces DsExpr to be compiled; DsBinds only
28                                 -- depends on DsExpr.hi-boot.
29 import Module
30 import UniqFM
31 import PackageConfig
32 import RdrName
33 import NameSet
34 import VarSet
35 import Rules
36 import CoreLint
37 import CoreFVs
38 import ErrUtils
39 import ListSetOps
40 import Outputable
41 import SrcLoc
42 import Maybes
43 import FastString
44 import Util
45 import Coverage
46 import IOEnv
47 import Data.IORef
48
49 \end{code}
50
51 %************************************************************************
52 %*                                                                      *
53 %*              The main function: deSugar
54 %*                                                                      *
55 %************************************************************************
56
57 \begin{code}
58 deSugar :: HscEnv -> ModLocation -> TcGblEnv -> IO (Maybe ModGuts)
59 -- Can modify PCS by faulting in more declarations
60
61 deSugar hsc_env 
62         mod_loc
63         tcg_env@(TcGblEnv { tcg_mod       = mod,
64                             tcg_src       = hsc_src,
65                             tcg_type_env  = type_env,
66                             tcg_imports   = imports,
67                             tcg_exports   = exports,
68                             tcg_dus       = dus, 
69                             tcg_inst_uses = dfun_uses_var,
70                             tcg_th_used   = th_var,
71                             tcg_keep      = keep_var,
72                             tcg_rdr_env   = rdr_env,
73                             tcg_fix_env   = fix_env,
74                             tcg_deprecs   = deprecs,
75                             tcg_binds     = binds,
76                             tcg_fords     = fords,
77                             tcg_rules     = rules,
78                             tcg_insts     = insts,
79                             tcg_fam_insts = fam_insts })
80   = do  { showPass dflags "Desugar"
81
82         -- Desugar the program
83         ; let export_set = availsToNameSet exports
84         ; let auto_scc = mkAutoScc mod export_set
85         ; let noDbgSites = []
86         ; mb_res <- case ghcMode dflags of
87                      JustTypecheck -> return (Just ([], [], NoStubs, noHpcInfo, noDbgSites))
88                      _        -> do (binds_cvr,ds_hpc_info) 
89                                               <- if opt_Hpc
90                                                  then addCoverageTicksToBinds dflags mod mod_loc binds
91                                                  else return (binds, noHpcInfo)
92                                     initDs hsc_env mod rdr_env type_env $ do
93                                         { core_prs <- dsTopLHsBinds auto_scc binds_cvr
94                                         ; (ds_fords, foreign_prs) <- dsForeigns fords
95                                         ; let all_prs = foreign_prs ++ core_prs
96                                               local_bndrs = mkVarSet (map fst all_prs)
97                                         ; ds_rules <- mappM (dsRule mod local_bndrs) rules
98                                         ; return (all_prs, catMaybes ds_rules, ds_fords, ds_hpc_info)
99                                         ; dbgSites_var <- getBkptSitesDs
100                                         ; dbgSites <- ioToIOEnv$ readIORef dbgSites_var
101                                         ; return (all_prs, catMaybes ds_rules, ds_fords, ds_hpc_info, dbgSites)
102                                         }
103         ; case mb_res of {
104            Nothing -> return Nothing ;
105            Just (all_prs, ds_rules, ds_fords,ds_hpc_info, dbgSites) -> do
106
107         {       -- Add export flags to bindings
108           keep_alive <- readIORef keep_var
109         ; let final_prs = addExportFlags ghci_mode export_set
110                                  keep_alive all_prs ds_rules
111               ds_binds  = [Rec final_prs]
112         -- Notice that we put the whole lot in a big Rec, even the foreign binds
113         -- When compiling PrelFloat, which defines data Float = F# Float#
114         -- we want F# to be in scope in the foreign marshalling code!
115         -- You might think it doesn't matter, but the simplifier brings all top-level
116         -- things into the in-scope set before simplifying; so we get no unfolding for F#!
117
118         -- Lint result if necessary
119         ; endPass dflags "Desugar" Opt_D_dump_ds ds_binds
120
121         -- Dump output
122         ; doIfSet (dopt Opt_D_dump_ds dflags) 
123                   (printDump (ppr_ds_rules ds_rules))
124
125         ; dfun_uses <- readIORef dfun_uses_var          -- What dfuns are used
126         ; th_used   <- readIORef th_var                 -- Whether TH is used
127         ; let used_names = allUses dus `unionNameSets` dfun_uses
128               pkgs | th_used   = insertList thPackageId (imp_dep_pkgs imports)
129                    | otherwise = imp_dep_pkgs imports
130
131               dep_mods = eltsUFM (delFromUFM (imp_dep_mods imports) (moduleName mod))
132                 -- M.hi-boot can be in the imp_dep_mods, but we must remove
133                 -- it before recording the modules on which this one depends!
134                 -- (We want to retain M.hi-boot in imp_dep_mods so that 
135                 --  loadHiBootInterface can see if M's direct imports depend 
136                 --  on M.hi-boot, and hence that we should do the hi-boot consistency 
137                 --  check.)
138
139               dir_imp_mods = imp_mods imports
140
141         ; usages <- mkUsageInfo hsc_env dir_imp_mods dep_mods used_names
142
143         ; let 
144                 -- Modules don't compare lexicographically usually, 
145                 -- but we want them to do so here.
146              le_mod :: Module -> Module -> Bool  
147              le_mod m1 m2 = moduleNameFS (moduleName m1) 
148                                 <= moduleNameFS (moduleName m2)
149              le_dep_mod :: (ModuleName, IsBootInterface) -> (ModuleName, IsBootInterface) -> Bool        
150              le_dep_mod (m1,_) (m2,_) = moduleNameFS m1 <= moduleNameFS m2
151
152              deps = Deps { dep_mods   = sortLe le_dep_mod dep_mods,
153                            dep_pkgs   = sortLe (<=)   pkgs,     
154                            dep_orphs  = sortLe le_mod (imp_orphs  imports),
155                            dep_finsts = sortLe le_mod (imp_finsts imports) }
156                 -- sort to get into canonical order
157
158              mod_guts = ModGuts {       
159                 mg_module    = mod,
160                 mg_boot      = isHsBoot hsc_src,
161                 mg_exports   = exports,
162                 mg_deps      = deps,
163                 mg_usages    = usages,
164                 mg_dir_imps  = [m | (m,_,_) <- moduleEnvElts dir_imp_mods],
165                 mg_rdr_env   = rdr_env,
166                 mg_fix_env   = fix_env,
167                 mg_deprecs   = deprecs,
168                 mg_types     = type_env,
169                 mg_insts     = insts,
170                 mg_fam_insts = fam_insts,
171                 mg_rules     = ds_rules,
172                 mg_binds     = ds_binds,
173                 mg_foreign   = ds_fords,
174                 mg_hpc_info  = ds_hpc_info,
175                 mg_dbg_sites = dbgSites }
176         ; return (Just mod_guts)
177         }}}
178
179   where
180     dflags    = hsc_dflags hsc_env
181     ghci_mode = ghcMode (hsc_dflags hsc_env)
182
183 mkAutoScc :: Module -> NameSet -> AutoScc
184 mkAutoScc mod exports
185   | not opt_SccProfilingOn      -- No profiling
186   = NoSccs              
187   | opt_AutoSccsOnAllToplevs    -- Add auto-scc on all top-level things
188   = AddSccs mod (\id -> True)
189   | opt_AutoSccsOnExportedToplevs       -- Only on exported things
190   = AddSccs mod (\id -> idName id `elemNameSet` exports)
191   | otherwise
192   = NoSccs
193
194
195 deSugarExpr :: HscEnv
196             -> Module -> GlobalRdrEnv -> TypeEnv 
197             -> LHsExpr Id
198             -> IO (Maybe CoreExpr)
199 -- Prints its own errors; returns Nothing if error occurred
200
201 deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
202   = do  { let dflags = hsc_dflags hsc_env
203         ; showPass dflags "Desugar"
204
205         -- Do desugaring
206         ; mb_core_expr <- initDs hsc_env this_mod rdr_env type_env $
207                           dsLExpr tc_expr
208
209         ; case mb_core_expr of {
210             Nothing   -> return Nothing ;
211             Just expr -> do {
212
213                 -- Dump output
214           dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr expr)
215
216         ; return (Just expr) } } }
217
218 --              addExportFlags
219 -- Set the no-discard flag if either 
220 --      a) the Id is exported
221 --      b) it's mentioned in the RHS of an orphan rule
222 --      c) it's in the keep-alive set
223 --
224 -- It means that the binding won't be discarded EVEN if the binding
225 -- ends up being trivial (v = w) -- the simplifier would usually just 
226 -- substitute w for v throughout, but we don't apply the substitution to
227 -- the rules (maybe we should?), so this substitution would make the rule
228 -- bogus.
229
230 -- You might wonder why exported Ids aren't already marked as such;
231 -- it's just because the type checker is rather busy already and
232 -- I didn't want to pass in yet another mapping.
233
234 addExportFlags ghci_mode exports keep_alive prs rules
235   = [(add_export bndr, rhs) | (bndr,rhs) <- prs]
236   where
237     add_export bndr
238         | dont_discard bndr = setIdExported bndr
239         | otherwise         = bndr
240
241     orph_rhs_fvs = unionVarSets [ ruleRhsFreeVars rule
242                                 | rule <- rules, 
243                                   not (isLocalRule rule) ]
244         -- A non-local rule keeps alive the free vars of its right-hand side. 
245         -- (A "non-local" is one whose head function is not locally defined.)
246         -- Local rules are (later, after gentle simplification) 
247         -- attached to the Id, and that keeps the rhs free vars alive.
248
249     dont_discard bndr = is_exported name
250                      || name `elemNameSet` keep_alive
251                      || bndr `elemVarSet` orph_rhs_fvs 
252                      where
253                         name = idName bndr
254
255         -- In interactive mode, we don't want to discard any top-level
256         -- entities at all (eg. do not inline them away during
257         -- simplification), and retain them all in the TypeEnv so they are
258         -- available from the command line.
259         --
260         -- isExternalName separates the user-defined top-level names from those
261         -- introduced by the type checker.
262     is_exported :: Name -> Bool
263     is_exported | ghci_mode == Interactive = isExternalName
264                 | otherwise                = (`elemNameSet` exports)
265
266 ppr_ds_rules [] = empty
267 ppr_ds_rules rules
268   = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
269     pprRules rules
270 \end{code}
271
272
273
274 %************************************************************************
275 %*                                                                      *
276 %*              Desugaring transformation rules
277 %*                                                                      *
278 %************************************************************************
279
280 \begin{code}
281 dsRule :: Module -> IdSet -> LRuleDecl Id -> DsM (Maybe CoreRule)
282 dsRule mod in_scope (L loc (HsRule name act vars lhs tv_lhs rhs fv_rhs))
283   = putSrcSpanDs loc $ 
284     do  { let bndrs     = [var | RuleBndr (L _ var) <- vars]
285         ; lhs'  <- dsLExpr lhs
286         ; rhs'  <- dsLExpr rhs
287
288         ; case decomposeRuleLhs bndrs lhs' of {
289                 Nothing -> do { warnDs msg; return Nothing } ;
290                 Just (bndrs', fn_id, args) -> do
291         
292         -- Substitute the dict bindings eagerly,
293         -- and take the body apart into a (f args) form
294         { let local_rule = nameIsLocalOrFrom mod fn_name
295                 -- NB we can't use isLocalId in the orphan test, 
296                 -- because isLocalId isn't true of class methods
297               fn_name   = idName fn_id
298               lhs_names = fn_name : nameSetToList (exprsFreeNames args)
299                 -- No need to delete bndrs, because
300                 -- exprsFreeNames finds only External names
301
302                 -- A rule is an orphan only if none of the variables
303                 -- mentioned on its left-hand side are locally defined
304               orph = case filter (nameIsLocalOrFrom mod) lhs_names of
305                         (n:ns) -> Just (nameOccName n)
306                         []     -> Nothing
307
308               rule = Rule { ru_name = name, ru_fn = fn_name, ru_act = act,
309                             ru_bndrs = bndrs', ru_args = args, ru_rhs = rhs', 
310                             ru_rough = roughTopNames args, 
311                             ru_local = local_rule, ru_orph = orph }
312         ; return (Just rule)
313         } } }
314   where
315     msg = hang (ptext SLIT("RULE left-hand side too complicated to desugar; ignored"))
316              2 (ppr lhs)
317 \end{code}