2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[Desugar]{@deSugar@: the main function}
7 module Desugar ( deSugar, deSugarExpr ) where
9 #include "HsVersions.h"
11 import DynFlags ( DynFlag(..), DynFlags(..), dopt, GhcMode(..) )
12 import StaticFlags ( opt_SccProfilingOn )
13 import DriverPhases ( isHsBoot )
14 import HscTypes ( ModGuts(..), HscEnv(..),
15 Dependencies(..), ForeignStubs(..), TypeEnv, IsBootInterface )
16 import HsSyn ( RuleDecl(..), RuleBndr(..), LHsExpr, LRuleDecl )
17 import TcRnTypes ( TcGblEnv(..), ImportAvails(..) )
18 import MkIface ( mkUsageInfo )
19 import Id ( Id, setIdExported, idName )
20 import Name ( Name, isExternalName, nameIsLocalOrFrom, nameOccName )
22 import PprCore ( pprRules, pprCoreExpr )
24 import DsExpr ( dsLExpr )
25 import DsBinds ( dsTopLHsBinds, decomposeRuleLhs, AutoScc(..) )
26 import DsForeign ( dsForeigns )
27 import DsExpr () -- Forces DsExpr to be compiled; DsBinds only
28 -- depends on DsExpr.hi-boot.
30 import UniqFM ( eltsUFM, delFromUFM )
31 import PackageConfig ( thPackageId )
32 import RdrName ( GlobalRdrEnv )
35 import Rules ( roughTopNames )
36 import CoreLint ( showPass, endPass )
37 import CoreFVs ( ruleRhsFreeVars, exprsFreeNames )
38 import ErrUtils ( doIfSet, dumpIfSet_dyn )
39 import ListSetOps ( insertList )
41 import SrcLoc ( Located(..) )
42 import DATA_IOREF ( readIORef )
43 import Maybes ( catMaybes )
45 import Util ( sortLe )
48 %************************************************************************
50 %* The main function: deSugar
52 %************************************************************************
55 deSugar :: HscEnv -> TcGblEnv -> IO (Maybe ModGuts)
56 -- Can modify PCS by faulting in more declarations
59 tcg_env@(TcGblEnv { tcg_mod = mod,
61 tcg_type_env = type_env,
62 tcg_imports = imports,
63 tcg_exports = exports,
65 tcg_inst_uses = dfun_uses_var,
68 tcg_rdr_env = rdr_env,
69 tcg_fix_env = fix_env,
70 tcg_deprecs = deprecs,
75 = do { showPass dflags "Desugar"
77 -- Desugar the program
78 ; mb_res <- case ghcMode dflags of
79 JustTypecheck -> return (Just ([], [], NoStubs))
80 _ -> initDs hsc_env mod rdr_env type_env $ do
81 { core_prs <- dsTopLHsBinds auto_scc binds
82 ; (ds_fords, foreign_prs) <- dsForeigns fords
83 ; let all_prs = foreign_prs ++ core_prs
84 local_bndrs = mkVarSet (map fst all_prs)
85 ; ds_rules <- mappM (dsRule mod local_bndrs) rules
86 ; return (all_prs, catMaybes ds_rules, ds_fords)
89 Nothing -> return Nothing ;
90 Just (all_prs, ds_rules, ds_fords) -> do
92 { -- Add export flags to bindings
93 keep_alive <- readIORef keep_var
94 ; let final_prs = addExportFlags ghci_mode exports keep_alive
96 ds_binds = [Rec final_prs]
97 -- Notice that we put the whole lot in a big Rec, even the foreign binds
98 -- When compiling PrelFloat, which defines data Float = F# Float#
99 -- we want F# to be in scope in the foreign marshalling code!
100 -- You might think it doesn't matter, but the simplifier brings all top-level
101 -- things into the in-scope set before simplifying; so we get no unfolding for F#!
103 -- Lint result if necessary
104 ; endPass dflags "Desugar" Opt_D_dump_ds ds_binds
107 ; doIfSet (dopt Opt_D_dump_ds dflags)
108 (printDump (ppr_ds_rules ds_rules))
110 ; dfun_uses <- readIORef dfun_uses_var -- What dfuns are used
111 ; th_used <- readIORef th_var -- Whether TH is used
112 ; let used_names = allUses dus `unionNameSets` dfun_uses
113 pkgs | th_used = insertList thPackageId (imp_dep_pkgs imports)
114 | otherwise = imp_dep_pkgs imports
116 dep_mods = eltsUFM (delFromUFM (imp_dep_mods imports) (moduleName mod))
117 -- M.hi-boot can be in the imp_dep_mods, but we must remove
118 -- it before recording the modules on which this one depends!
119 -- (We want to retain M.hi-boot in imp_dep_mods so that
120 -- loadHiBootInterface can see if M's direct imports depend
121 -- on M.hi-boot, and hence that we should do the hi-boot consistency
124 dir_imp_mods = imp_mods imports
126 ; usages <- mkUsageInfo hsc_env dir_imp_mods dep_mods used_names
129 -- Modules don't compare lexicographically usually,
130 -- but we want them to do so here.
131 le_mod :: Module -> Module -> Bool
132 le_mod m1 m2 = moduleNameFS (moduleName m1)
133 <= moduleNameFS (moduleName m2)
134 le_dep_mod :: (ModuleName, IsBootInterface) -> (ModuleName, IsBootInterface) -> Bool
135 le_dep_mod (m1,_) (m2,_) = moduleNameFS m1 <= moduleNameFS m2
137 deps = Deps { dep_mods = sortLe le_dep_mod dep_mods,
138 dep_pkgs = sortLe (<=) pkgs,
139 dep_orphs = sortLe le_mod (imp_orphs imports) }
140 -- sort to get into canonical order
144 mg_boot = isHsBoot hsc_src,
145 mg_exports = exports,
148 mg_dir_imps = [m | (m,_,_) <- moduleEnvElts dir_imp_mods],
149 mg_rdr_env = rdr_env,
150 mg_fix_env = fix_env,
151 mg_deprecs = deprecs,
156 mg_foreign = ds_fords }
158 ; return (Just mod_guts)
162 dflags = hsc_dflags hsc_env
163 ghci_mode = ghcMode (hsc_dflags hsc_env)
164 auto_scc | opt_SccProfilingOn = TopLevel
167 deSugarExpr :: HscEnv
168 -> Module -> GlobalRdrEnv -> TypeEnv
170 -> IO (Maybe CoreExpr)
171 -- Prints its own errors; returns Nothing if error occurred
173 deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
174 = do { let dflags = hsc_dflags hsc_env
175 ; showPass dflags "Desugar"
178 ; mb_core_expr <- initDs hsc_env this_mod rdr_env type_env $
181 ; case mb_core_expr of {
182 Nothing -> return Nothing ;
186 dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr expr)
188 ; return (Just expr) } } }
191 -- Set the no-discard flag if either
192 -- a) the Id is exported
193 -- b) it's mentioned in the RHS of an orphan rule
194 -- c) it's in the keep-alive set
196 -- It means that the binding won't be discarded EVEN if the binding
197 -- ends up being trivial (v = w) -- the simplifier would usually just
198 -- substitute w for v throughout, but we don't apply the substitution to
199 -- the rules (maybe we should?), so this substitution would make the rule
202 -- You might wonder why exported Ids aren't already marked as such;
203 -- it's just because the type checker is rather busy already and
204 -- I didn't want to pass in yet another mapping.
206 addExportFlags ghci_mode exports keep_alive prs rules
207 = [(add_export bndr, rhs) | (bndr,rhs) <- prs]
210 | dont_discard bndr = setIdExported bndr
213 orph_rhs_fvs = unionVarSets [ ruleRhsFreeVars rule
215 not (isLocalRule rule) ]
216 -- A non-local rule keeps alive the free vars of its right-hand side.
217 -- (A "non-local" is one whose head function is not locally defined.)
218 -- Local rules are (later, after gentle simplification)
219 -- attached to the Id, and that keeps the rhs free vars alive.
221 dont_discard bndr = is_exported name
222 || name `elemNameSet` keep_alive
223 || bndr `elemVarSet` orph_rhs_fvs
227 -- In interactive mode, we don't want to discard any top-level
228 -- entities at all (eg. do not inline them away during
229 -- simplification), and retain them all in the TypeEnv so they are
230 -- available from the command line.
232 -- isExternalName separates the user-defined top-level names from those
233 -- introduced by the type checker.
234 is_exported :: Name -> Bool
235 is_exported | ghci_mode == Interactive = isExternalName
236 | otherwise = (`elemNameSet` exports)
238 ppr_ds_rules [] = empty
240 = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
246 %************************************************************************
248 %* Desugaring transformation rules
250 %************************************************************************
253 dsRule :: Module -> IdSet -> LRuleDecl Id -> DsM (Maybe CoreRule)
254 dsRule mod in_scope (L loc (HsRule name act vars lhs tv_lhs rhs fv_rhs))
256 do { let bndrs = [var | RuleBndr (L _ var) <- vars]
257 ; lhs' <- dsLExpr lhs
258 ; rhs' <- dsLExpr rhs
260 ; case decomposeRuleLhs bndrs lhs' of {
261 Nothing -> do { warnDs msg; return Nothing } ;
262 Just (bndrs', fn_id, args) -> do
264 -- Substitute the dict bindings eagerly,
265 -- and take the body apart into a (f args) form
266 { let local_rule = nameIsLocalOrFrom mod fn_name
267 -- NB we can't use isLocalId in the orphan test,
268 -- because isLocalId isn't true of class methods
269 fn_name = idName fn_id
270 lhs_names = fn_name : nameSetToList (exprsFreeNames args)
271 -- No need to delete bndrs, because
272 -- exprsFreeNames finds only External names
273 orph = case filter (nameIsLocalOrFrom mod) lhs_names of
274 (n:ns) -> Just (nameOccName n)
277 rule = Rule { ru_name = name, ru_fn = fn_name, ru_act = act,
278 ru_bndrs = bndrs', ru_args = args, ru_rhs = rhs',
279 ru_rough = roughTopNames args,
280 ru_local = local_rule, ru_orph = orph }
284 msg = hang (ptext SLIT("RULE left-hand side too complicated to desugar; ignored"))