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 CmdLineOpts ( DynFlag(..), dopt, opt_SccProfilingOn )
12 import HscTypes ( ModGuts(..), ModGuts, HscEnv(..), GhciMode(..),
13 Dependencies(..), TypeEnv, IsBootInterface, unQualInScope )
14 import HsSyn ( RuleDecl(..), RuleBndr(..), HsExpr(..), LHsExpr,
15 HsBindGroup(..), LRuleDecl, HsBind(..) )
16 import TcRnTypes ( TcGblEnv(..), ImportAvails(..) )
17 import MkIface ( mkUsageInfo )
18 import Id ( Id, setIdLocalExported, idName )
19 import Name ( Name, isExternalName )
21 import PprCore ( pprIdRules, pprCoreExpr )
22 import Subst ( SubstResult(..), substExpr, mkSubst, extendIdSubstList )
24 import DsExpr ( dsLExpr )
25 import DsBinds ( dsHsBinds, 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, ModuleName, moduleEnvElts, delModuleEnv, moduleNameFS )
31 import RdrName ( GlobalRdrEnv )
35 import Bag ( Bag, isEmptyBag, mapBag, emptyBag, bagToList )
36 import CoreLint ( showPass, endPass )
37 import CoreFVs ( ruleRhsFreeVars )
38 import Packages ( thPackage )
39 import ErrUtils ( doIfSet, dumpIfSet_dyn, pprBagOfWarnings,
40 mkWarnMsg, errorsFound, WarnMsg )
41 import ListSetOps ( insertList )
43 import UniqSupply ( mkSplitUniqSupply )
44 import SrcLoc ( Located(..), SrcSpan, unLoc )
45 import DATA_IOREF ( readIORef )
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,
62 tcg_type_env = type_env,
63 tcg_imports = imports,
64 tcg_exports = exports,
66 tcg_inst_uses = dfun_uses_var,
68 tcg_rdr_env = rdr_env,
69 tcg_fix_env = fix_env,
70 tcg_deprecs = deprecs,
72 = do { showPass dflags "Desugar"
75 ; (results, warnings) <- initDs hsc_env mod type_env $
76 dsProgram ghci_mode tcg_env
78 ; let { (ds_binds, ds_rules, ds_fords) = results
79 ; warns = mapBag mk_warn warnings
82 -- If warnings are considered errors, leave.
83 ; if errorsFound dflags (warns, emptyBag)
84 then return (warns, Nothing)
87 -- Lint result if necessary
88 { endPass dflags "Desugar" Opt_D_dump_ds ds_binds
91 ; doIfSet (dopt Opt_D_dump_ds dflags)
92 (printDump (ppr_ds_rules ds_rules))
94 ; dfun_uses <- readIORef dfun_uses_var -- What dfuns are used
95 ; th_used <- readIORef th_var
96 ; let used_names = allUses dus `unionNameSets` dfun_uses
97 pkgs | th_used = insertList thPackage (imp_dep_pkgs imports)
98 | otherwise = imp_dep_pkgs imports
100 dep_mods = moduleEnvElts (delModuleEnv (imp_dep_mods imports) mod)
101 -- M.hi-boot can be in the imp_dep_mods, but we must remove
102 -- it before recording the modules on which this one depends!
103 -- (We want to retain M.hi-boot in imp_dep_mods so that
104 -- loadHiBootInterface can see if M's direct imports depend
105 -- on M.hi-boot, and hence that we should do the hi-boot consistency
108 dir_imp_mods = imp_mods imports
110 ; usages <- mkUsageInfo hsc_env dir_imp_mods dep_mods used_names
113 -- ModuleNames don't compare lexicographically usually,
114 -- but we want them to do so here.
115 le_mod :: ModuleName -> ModuleName -> Bool
116 le_mod m1 m2 = moduleNameFS m1 <= moduleNameFS m2
117 le_dep_mod :: (ModuleName, IsBootInterface) -> (ModuleName, IsBootInterface) -> Bool
118 le_dep_mod (m1,_) (m2,_) = m1 `le_mod` m2
120 deps = Deps { dep_mods = sortLe le_dep_mod dep_mods,
121 dep_pkgs = sortLe (<=) pkgs,
122 dep_orphs = sortLe le_mod (imp_orphs imports) }
123 -- sort to get into canonical order
127 mg_exports = exports,
130 mg_dir_imps = [m | (m,_,_) <- moduleEnvElts dir_imp_mods],
131 mg_rdr_env = rdr_env,
132 mg_fix_env = fix_env,
133 mg_deprecs = deprecs,
138 mg_foreign = ds_fords }
140 ; return (warns, Just mod_guts)
144 dflags = hsc_dflags hsc_env
145 ghci_mode = hsc_mode hsc_env
146 print_unqual = unQualInScope rdr_env
148 -- Desugarer warnings are SDocs; here we
149 -- add the info about whether or not to print unqualified
150 mk_warn :: (SrcSpan,SDoc) -> WarnMsg
151 mk_warn (loc, sdoc) = mkWarnMsg loc print_unqual sdoc
154 deSugarExpr :: HscEnv
155 -> Module -> GlobalRdrEnv -> TypeEnv
158 deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
159 = do { showPass dflags "Desugar"
160 ; us <- mkSplitUniqSupply 'd'
163 ; (core_expr, ds_warns) <- initDs hsc_env this_mod type_env $
166 -- Display any warnings
167 -- Note: if -Werror is used, we don't signal an error here.
168 ; doIfSet (not (isEmptyBag ds_warns))
169 (printErrs (pprBagOfWarnings (mapBag mk_warn ds_warns)))
172 ; dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr core_expr)
177 dflags = hsc_dflags hsc_env
178 print_unqual = unQualInScope rdr_env
180 mk_warn :: (SrcSpan,SDoc) -> WarnMsg
181 mk_warn (loc,sdoc) = mkWarnMsg loc print_unqual sdoc
184 dsProgram ghci_mode (TcGblEnv { tcg_exports = exports,
185 tcg_keep = keep_alive,
189 = dsHsBinds auto_scc binds [] `thenDs` \ core_prs ->
190 dsForeigns fords `thenDs` \ (ds_fords, foreign_prs) ->
192 all_prs = foreign_prs ++ core_prs
193 local_bndrs = mkVarSet (map fst all_prs)
195 mappM (dsRule local_bndrs) rules `thenDs` \ ds_rules ->
197 final_prs = addExportFlags ghci_mode exports keep_alive
198 local_bndrs all_prs ds_rules
199 ds_binds = [Rec final_prs]
200 -- Notice that we put the whole lot in a big Rec, even the foreign binds
201 -- When compiling PrelFloat, which defines data Float = F# Float#
202 -- we want F# to be in scope in the foreign marshalling code!
203 -- You might think it doesn't matter, but the simplifier brings all top-level
204 -- things into the in-scope set before simplifying; so we get no unfolding for F#!
206 returnDs (ds_binds, ds_rules, ds_fords)
208 auto_scc | opt_SccProfilingOn = TopLevel
212 -- Set the no-discard flag if either
213 -- a) the Id is exported
214 -- b) it's mentioned in the RHS of an orphan rule
215 -- c) it's in the keep-alive set
217 -- It means that the binding won't be discarded EVEN if the binding
218 -- ends up being trivial (v = w) -- the simplifier would usually just
219 -- substitute w for v throughout, but we don't apply the substitution to
220 -- the rules (maybe we should?), so this substitution would make the rule
223 -- You might wonder why exported Ids aren't already marked as such;
224 -- it's just because the type checker is rather busy already and
225 -- I didn't want to pass in yet another mapping.
227 addExportFlags ghci_mode exports keep_alive bndrs prs rules
228 = [(add_export bndr, rhs) | (bndr,rhs) <- prs]
230 add_export bndr | dont_discard bndr = setIdLocalExported bndr
233 orph_rhs_fvs = unionVarSets [ ruleRhsFreeVars rule
234 | (id, rule) <- rules,
235 not (id `elemVarSet` bndrs) ]
236 -- An orphan rule must keep alive the free vars
237 -- of its right-hand side.
238 -- Non-orphan rules are attached to the Id (bndr_with_rules above)
239 -- and that keeps the rhs free vars alive
241 dont_discard bndr = is_exported name
242 || name `elemNameSet` keep_alive
243 || bndr `elemVarSet` orph_rhs_fvs
247 -- In interactive mode, we don't want to discard any top-level
248 -- entities at all (eg. do not inline them away during
249 -- simplification), and retain them all in the TypeEnv so they are
250 -- available from the command line.
252 -- isExternalName separates the user-defined top-level names from those
253 -- introduced by the type checker.
254 is_exported :: Name -> Bool
255 is_exported | ghci_mode == Interactive = isExternalName
256 | otherwise = (`elemNameSet` exports)
258 ppr_ds_rules [] = empty
260 = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
266 %************************************************************************
268 %* Desugaring transformation rules
270 %************************************************************************
273 dsRule :: IdSet -> LRuleDecl Id -> DsM (Id, CoreRule)
274 dsRule in_scope (L loc (HsRule name act vars lhs rhs))
276 ds_lhs all_vars lhs `thenDs` \ (fn, args) ->
277 dsLExpr rhs `thenDs` \ core_rhs ->
278 returnDs (fn, Rule name act tpl_vars args core_rhs)
280 tpl_vars = [var | RuleBndr (L _ var) <- vars]
281 all_vars = mkInScopeSet (extendVarSetList in_scope tpl_vars)
287 (HsLet [HsBindGroup dict_binds _ _] body) -> (dict_binds, body)
288 other -> (emptyBag, lhs)
290 mappM ds_dict_bind (bagToList dict_binds) `thenDs` \ dict_binds' ->
291 dsLExpr body `thenDs` \ body' ->
293 -- Substitute the dict bindings eagerly,
294 -- and take the body apart into a (f args) form
296 subst = extendIdSubstList (mkSubst all_vars) pairs
297 pairs = [(id, ContEx subst rhs) | (id,rhs) <- dict_binds']
298 -- Note recursion here... substitution won't terminate
299 -- if there is genuine recursion... which there isn't
300 body'' = substExpr subst body'
303 -- Now unpack the resulting body
305 pair = case collectArgs body'' of
306 (Var fn, args) -> (fn, args)
307 other -> pprPanic "dsRule" (ppr lhs)
311 ds_dict_bind (L _ (VarBind id rhs)) =
312 dsLExpr rhs `thenDs` \ rhs' ->