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(..), ModGuts, HscEnv(..),
15 Dependencies(..), TypeEnv, IsBootInterface )
16 import HsSyn ( RuleDecl(..), RuleBndr(..), HsExpr(..), LHsExpr,
17 HsBindGroup(..), LRuleDecl, HsBind(..) )
18 import TcRnTypes ( TcGblEnv(..), ImportAvails(..) )
19 import MkIface ( mkUsageInfo )
20 import Id ( Id, setIdExported, idName, idIsFrom )
21 import Name ( Name, isExternalName )
23 import PprCore ( pprIdRules, pprCoreExpr )
24 import CoreSubst ( substExpr, mkSubst )
26 import DsExpr ( dsLExpr )
27 import DsBinds ( dsHsBinds, AutoScc(..) )
28 import DsForeign ( dsForeigns )
29 import DsExpr () -- Forces DsExpr to be compiled; DsBinds only
30 -- depends on DsExpr.hi-boot.
31 import Module ( Module, moduleEnvElts, delModuleEnv, moduleFS )
33 import RdrName ( GlobalRdrEnv )
37 import Bag ( Bag, isEmptyBag, emptyBag, bagToList )
38 import CoreLint ( showPass, endPass )
39 import CoreFVs ( ruleRhsFreeVars )
40 import Packages ( PackageState(thPackageId), PackageIdH(..) )
41 import ErrUtils ( doIfSet, dumpIfSet_dyn, pprBagOfWarnings,
42 errorsFound, WarnMsg )
43 import ListSetOps ( insertList )
45 import UniqSupply ( mkSplitUniqSupply )
46 import SrcLoc ( Located(..), unLoc )
47 import DATA_IOREF ( readIORef )
49 import Util ( sortLe )
52 %************************************************************************
54 %* The main function: deSugar
56 %************************************************************************
59 deSugar :: HscEnv -> TcGblEnv -> IO (Bag WarnMsg, Maybe ModGuts)
60 -- Can modify PCS by faulting in more declarations
63 tcg_env@(TcGblEnv { tcg_mod = mod,
65 tcg_type_env = type_env,
66 tcg_imports = imports,
67 tcg_exports = exports,
69 tcg_inst_uses = dfun_uses_var,
72 tcg_rdr_env = rdr_env,
73 tcg_fix_env = fix_env,
74 tcg_deprecs = deprecs,
79 = do { showPass dflags "Desugar"
81 -- Desugar the program
82 ; ((all_prs, ds_rules, ds_fords), warns)
83 <- initDs hsc_env mod rdr_env type_env $ do
84 { core_prs <- dsHsBinds auto_scc binds []
85 ; (ds_fords, foreign_prs) <- dsForeigns fords
86 ; let all_prs = foreign_prs ++ core_prs
87 local_bndrs = mkVarSet (map fst all_prs)
88 ; ds_rules <- mappM (dsRule mod local_bndrs) rules
89 ; return (all_prs, 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 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,
156 mg_dir_imps = [m | (m,_,_) <- moduleEnvElts dir_imp_mods],
157 mg_rdr_env = rdr_env,
158 mg_fix_env = fix_env,
159 mg_deprecs = deprecs,
164 mg_foreign = ds_fords }
166 ; return (warns, Just mod_guts)
170 dflags = hsc_dflags hsc_env
171 ghci_mode = ghcMode (hsc_dflags hsc_env)
172 auto_scc | opt_SccProfilingOn = TopLevel
175 deSugarExpr :: HscEnv
176 -> Module -> GlobalRdrEnv -> TypeEnv
179 deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
180 = do { showPass dflags "Desugar"
181 ; us <- mkSplitUniqSupply 'd'
184 ; (core_expr, ds_warns) <- initDs hsc_env this_mod rdr_env type_env $
187 -- Display any warnings
188 -- Note: if -Werror is used, we don't signal an error here.
189 ; doIfSet (not (isEmptyBag ds_warns))
190 (printErrs (pprBagOfWarnings ds_warns))
193 ; dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr core_expr)
198 dflags = hsc_dflags hsc_env
202 -- Set the no-discard flag if either
203 -- a) the Id is exported
204 -- b) it's mentioned in the RHS of an orphan rule
205 -- c) it's in the keep-alive set
207 -- It means that the binding won't be discarded EVEN if the binding
208 -- ends up being trivial (v = w) -- the simplifier would usually just
209 -- substitute w for v throughout, but we don't apply the substitution to
210 -- the rules (maybe we should?), so this substitution would make the rule
213 -- You might wonder why exported Ids aren't already marked as such;
214 -- it's just because the type checker is rather busy already and
215 -- I didn't want to pass in yet another mapping.
217 addExportFlags ghci_mode exports keep_alive prs rules
218 = [(add_export bndr, rhs) | (bndr,rhs) <- prs]
221 | dont_discard bndr = setIdExported bndr
224 orph_rhs_fvs = unionVarSets [ ruleRhsFreeVars rule
225 | IdCoreRule _ is_orphan_rule rule <- rules,
227 -- An orphan rule keeps alive the free vars of its right-hand side.
228 -- Non-orphan rules are (later, after gentle simplification)
229 -- attached to the Id and that keeps the rhs free vars alive
231 dont_discard bndr = is_exported name
232 || name `elemNameSet` keep_alive
233 || bndr `elemVarSet` orph_rhs_fvs
237 -- In interactive mode, we don't want to discard any top-level
238 -- entities at all (eg. do not inline them away during
239 -- simplification), and retain them all in the TypeEnv so they are
240 -- available from the command line.
242 -- isExternalName separates the user-defined top-level names from those
243 -- introduced by the type checker.
244 is_exported :: Name -> Bool
245 is_exported | ghci_mode == Interactive = isExternalName
246 | otherwise = (`elemNameSet` exports)
248 ppr_ds_rules [] = empty
250 = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
256 %************************************************************************
258 %* Desugaring transformation rules
260 %************************************************************************
263 dsRule :: Module -> IdSet -> LRuleDecl Id -> DsM IdCoreRule
264 dsRule mod in_scope (L loc (HsRule name act vars lhs rhs))
266 ds_lhs all_vars lhs `thenDs` \ (fn, args) ->
267 dsLExpr rhs `thenDs` \ core_rhs ->
268 returnDs (IdCoreRule fn (is_orphan fn) (Rule name act tpl_vars args core_rhs))
270 tpl_vars = [var | RuleBndr (L _ var) <- vars]
271 all_vars = mkInScopeSet (extendVarSetList in_scope tpl_vars)
272 is_orphan id = not (idIsFrom mod id)
273 -- NB we can't use isLocalId in the orphan test,
274 -- because isLocalId isn't true of class methods
280 (HsLet [HsBindGroup dict_binds _ _] body) -> (dict_binds, body)
281 other -> (emptyBag, lhs)
283 mappM ds_dict_bind (bagToList dict_binds) `thenDs` \ dict_binds' ->
284 dsLExpr body `thenDs` \ body' ->
286 -- Substitute the dict bindings eagerly,
287 -- and take the body apart into a (f args) form
289 subst = mkSubst all_vars emptyVarEnv (mkVarEnv id_pairs)
290 id_pairs = [(id, substExpr subst rhs) | (id,rhs) <- dict_binds']
291 -- Note recursion here... substitution won't terminate
292 -- if there is genuine recursion... which there isn't
294 body'' = substExpr subst body'
297 -- Now unpack the resulting body
299 pair = case collectArgs body'' of
300 (Var fn, args) -> (fn, args)
301 other -> pprPanic "dsRule" (ppr lhs)
305 ds_dict_bind (L _ (VarBind id rhs)) =
306 dsLExpr rhs `thenDs` \ rhs' ->