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.
29 import Module ( Module, moduleEnvElts, delModuleEnv, moduleFS )
30 import RdrName ( GlobalRdrEnv )
33 import Bag ( Bag, isEmptyBag, emptyBag )
34 import Rules ( roughTopNames )
35 import CoreLint ( showPass, endPass )
36 import CoreFVs ( ruleRhsFreeVars, exprsFreeNames )
37 import Packages ( PackageState(thPackageId), PackageIdH(..) )
38 import ErrUtils ( doIfSet, dumpIfSet_dyn, printBagOfWarnings,
39 errorsFound, WarnMsg )
40 import ListSetOps ( insertList )
42 import UniqSupply ( mkSplitUniqSupply )
43 import SrcLoc ( Located(..) )
44 import DATA_IOREF ( readIORef )
45 import Maybes ( catMaybes )
47 import Util ( sortLe )
50 %************************************************************************
52 %* The main function: deSugar
54 %************************************************************************
57 deSugar :: HscEnv -> TcGblEnv -> IO (Bag WarnMsg, Maybe ModGuts)
58 -- Can modify PCS by faulting in more declarations
61 tcg_env@(TcGblEnv { tcg_mod = mod,
63 tcg_type_env = type_env,
64 tcg_imports = imports,
65 tcg_home_mods = home_mods,
66 tcg_exports = exports,
68 tcg_inst_uses = dfun_uses_var,
71 tcg_rdr_env = rdr_env,
72 tcg_fix_env = fix_env,
73 tcg_deprecs = deprecs,
78 = do { showPass dflags "Desugar"
80 -- Desugar the program
81 ; ((all_prs, ds_rules, ds_fords), warns)
82 <- case ghcMode (hsc_dflags hsc_env) of
83 JustTypecheck -> return (([], [], NoStubs), emptyBag)
84 _ -> initDs hsc_env mod rdr_env type_env $ do
85 { core_prs <- dsTopLHsBinds auto_scc binds
86 ; (ds_fords, foreign_prs) <- dsForeigns fords
87 ; let all_prs = foreign_prs ++ core_prs
88 local_bndrs = mkVarSet (map fst all_prs)
89 ; ds_rules <- mappM (dsRule mod local_bndrs) rules
90 ; return (all_prs, catMaybes ds_rules, ds_fords)
93 -- If warnings are considered errors, leave.
94 ; if errorsFound dflags (warns, emptyBag)
95 then return (warns, Nothing)
98 { -- Add export flags to bindings
99 keep_alive <- readIORef keep_var
100 ; let final_prs = addExportFlags ghci_mode exports keep_alive
102 ds_binds = [Rec final_prs]
103 -- Notice that we put the whole lot in a big Rec, even the foreign binds
104 -- When compiling PrelFloat, which defines data Float = F# Float#
105 -- we want F# to be in scope in the foreign marshalling code!
106 -- You might think it doesn't matter, but the simplifier brings all top-level
107 -- things into the in-scope set before simplifying; so we get no unfolding for F#!
109 -- Lint result if necessary
110 ; endPass dflags "Desugar" Opt_D_dump_ds ds_binds
113 ; doIfSet (dopt Opt_D_dump_ds dflags)
114 (printDump (ppr_ds_rules ds_rules))
116 ; dfun_uses <- readIORef dfun_uses_var -- What dfuns are used
117 ; th_used <- readIORef th_var -- Whether TH is used
118 ; let used_names = allUses dus `unionNameSets` dfun_uses
119 thPackage = thPackageId (pkgState dflags)
120 pkgs | ExtPackage th_id <- thPackage, th_used
121 = insertList th_id (imp_dep_pkgs imports)
123 = imp_dep_pkgs imports
125 dep_mods = moduleEnvElts (delModuleEnv (imp_dep_mods imports) mod)
126 -- M.hi-boot can be in the imp_dep_mods, but we must remove
127 -- it before recording the modules on which this one depends!
128 -- (We want to retain M.hi-boot in imp_dep_mods so that
129 -- loadHiBootInterface can see if M's direct imports depend
130 -- on M.hi-boot, and hence that we should do the hi-boot consistency
133 dir_imp_mods = imp_mods imports
135 ; usages <- mkUsageInfo hsc_env home_mods dir_imp_mods dep_mods used_names
138 -- Modules don't compare lexicographically usually,
139 -- but we want them to do so here.
140 le_mod :: Module -> Module -> Bool
141 le_mod m1 m2 = moduleFS m1 <= moduleFS m2
142 le_dep_mod :: (Module, IsBootInterface) -> (Module, IsBootInterface) -> Bool
143 le_dep_mod (m1,_) (m2,_) = m1 `le_mod` m2
145 deps = Deps { dep_mods = sortLe le_dep_mod dep_mods,
146 dep_pkgs = sortLe (<=) pkgs,
147 dep_orphs = sortLe le_mod (imp_orphs imports) }
148 -- sort to get into canonical order
152 mg_boot = isHsBoot hsc_src,
153 mg_exports = exports,
155 mg_home_mods = home_mods,
157 mg_dir_imps = [m | (m,_,_) <- moduleEnvElts dir_imp_mods],
158 mg_rdr_env = rdr_env,
159 mg_fix_env = fix_env,
160 mg_deprecs = deprecs,
165 mg_foreign = ds_fords }
167 ; return (warns, Just mod_guts)
171 dflags = hsc_dflags hsc_env
172 ghci_mode = ghcMode (hsc_dflags hsc_env)
173 auto_scc | opt_SccProfilingOn = TopLevel
176 deSugarExpr :: HscEnv
177 -> Module -> GlobalRdrEnv -> TypeEnv
180 deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
181 = do { showPass dflags "Desugar"
182 ; us <- mkSplitUniqSupply 'd'
185 ; (core_expr, ds_warns) <- initDs hsc_env this_mod rdr_env type_env $
188 -- Display any warnings
189 -- Note: if -Werror is used, we don't signal an error here.
190 ; doIfSet (not (isEmptyBag ds_warns))
191 (printBagOfWarnings dflags ds_warns)
194 ; dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr core_expr)
199 dflags = hsc_dflags hsc_env
203 -- Set the no-discard flag if either
204 -- a) the Id is exported
205 -- b) it's mentioned in the RHS of an orphan rule
206 -- c) it's in the keep-alive set
208 -- It means that the binding won't be discarded EVEN if the binding
209 -- ends up being trivial (v = w) -- the simplifier would usually just
210 -- substitute w for v throughout, but we don't apply the substitution to
211 -- the rules (maybe we should?), so this substitution would make the rule
214 -- You might wonder why exported Ids aren't already marked as such;
215 -- it's just because the type checker is rather busy already and
216 -- I didn't want to pass in yet another mapping.
218 addExportFlags ghci_mode exports keep_alive prs rules
219 = [(add_export bndr, rhs) | (bndr,rhs) <- prs]
222 | dont_discard bndr = setIdExported bndr
225 orph_rhs_fvs = unionVarSets [ ruleRhsFreeVars rule
227 not (isLocalRule rule) ]
228 -- A non-local rule keeps alive the free vars of its right-hand side.
229 -- (A "non-local" is one whose head function is not locally defined.)
230 -- Local rules are (later, after gentle simplification)
231 -- attached to the Id, and that keeps the rhs free vars alive.
233 dont_discard bndr = is_exported name
234 || name `elemNameSet` keep_alive
235 || bndr `elemVarSet` orph_rhs_fvs
239 -- In interactive mode, we don't want to discard any top-level
240 -- entities at all (eg. do not inline them away during
241 -- simplification), and retain them all in the TypeEnv so they are
242 -- available from the command line.
244 -- isExternalName separates the user-defined top-level names from those
245 -- introduced by the type checker.
246 is_exported :: Name -> Bool
247 is_exported | ghci_mode == Interactive = isExternalName
248 | otherwise = (`elemNameSet` exports)
250 ppr_ds_rules [] = empty
252 = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
258 %************************************************************************
260 %* Desugaring transformation rules
262 %************************************************************************
265 dsRule :: Module -> IdSet -> LRuleDecl Id -> DsM (Maybe CoreRule)
266 dsRule mod in_scope (L loc (HsRule name act vars lhs tv_lhs rhs fv_rhs))
268 do { let bndrs = [var | RuleBndr (L _ var) <- vars]
269 ; lhs' <- dsLExpr lhs
270 ; rhs' <- dsLExpr rhs
272 ; case decomposeRuleLhs bndrs lhs' of {
273 Nothing -> do { dsWarn msg; return Nothing } ;
274 Just (bndrs', fn_id, args) -> do
276 -- Substitute the dict bindings eagerly,
277 -- and take the body apart into a (f args) form
278 { let local_rule = nameIsLocalOrFrom mod fn_name
279 -- NB we can't use isLocalId in the orphan test,
280 -- because isLocalId isn't true of class methods
281 fn_name = idName fn_id
282 lhs_names = fn_name : nameSetToList (exprsFreeNames args)
283 -- No need to delete bndrs, because
284 -- exprsFreeNames finds only External names
285 orph = case filter (nameIsLocalOrFrom mod) lhs_names of
286 (n:ns) -> Just (nameOccName n)
289 rule = Rule { ru_name = name, ru_fn = fn_name, ru_act = act,
290 ru_bndrs = bndrs', ru_args = args, ru_rhs = rhs',
291 ru_rough = roughTopNames args,
292 ru_local = local_rule, ru_orph = orph }
296 msg = hang (ptext SLIT("RULE left-hand side too complicated to desugar; ignored"))