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,
14 unQualInScope, availsToNameSet )
15 import HsSyn ( RuleDecl(..), RuleBndr(..), HsExpr(..), LHsExpr,
16 HsBindGroup(..), LRuleDecl, HsBind(..) )
17 import TcRnTypes ( TcGblEnv(..), ImportAvails(..) )
18 import MkIface ( mkUsageInfo )
19 import Id ( Id, setIdLocalExported, idName )
20 import Name ( Name, isExternalName )
22 import PprCore ( pprIdRules, pprCoreExpr )
23 import Subst ( substExpr, mkSubst, mkInScopeSet )
25 import DsExpr ( dsLExpr )
26 import DsBinds ( dsHsBinds, AutoScc(..) )
27 import DsForeign ( dsForeigns )
28 import DsExpr () -- Forces DsExpr to be compiled; DsBinds only
29 -- depends on DsExpr.hi-boot.
30 import Module ( Module, moduleEnvElts, emptyModuleEnv )
32 import RdrName ( GlobalRdrEnv )
36 import Bag ( Bag, isEmptyBag, mapBag, emptyBag, bagToList )
37 import CoreLint ( showPass, endPass )
38 import CoreFVs ( ruleRhsFreeVars )
39 import Packages ( thPackage )
40 import ErrUtils ( doIfSet, dumpIfSet_dyn, pprBagOfWarnings,
41 mkWarnMsg, errorsFound, WarnMsg )
42 import ListSetOps ( insertList )
44 import UniqSupply ( mkSplitUniqSupply )
45 import SrcLoc ( Located(..), SrcSpan, unLoc )
46 import DATA_IOREF ( readIORef )
48 import Data.List ( sort )
51 %************************************************************************
53 %* The main function: deSugar
55 %************************************************************************
58 deSugar :: HscEnv -> TcGblEnv -> IO (Bag WarnMsg, Maybe ModGuts)
59 -- Can modify PCS by faulting in more declarations
62 tcg_env@(TcGblEnv { tcg_mod = mod,
63 tcg_type_env = type_env,
64 tcg_imports = imports,
65 tcg_exports = exports,
67 tcg_inst_uses = dfun_uses_var,
69 tcg_rdr_env = rdr_env,
70 tcg_fix_env = fix_env,
71 tcg_deprecs = deprecs,
73 = do { showPass dflags "Desugar"
76 ; let { is_boot = imp_dep_mods imports }
77 ; (results, warnings) <- initDs hsc_env mod type_env is_boot $
78 dsProgram ghci_mode tcg_env
80 ; let { (ds_binds, ds_rules, ds_fords) = results
81 ; warns = mapBag mk_warn warnings
84 -- If warnings are considered errors, leave.
85 ; if errorsFound dflags (warns, emptyBag)
86 then return (warns, Nothing)
89 -- Lint result if necessary
90 { endPass dflags "Desugar" Opt_D_dump_ds ds_binds
93 ; doIfSet (dopt Opt_D_dump_ds dflags)
94 (printDump (ppr_ds_rules ds_rules))
96 ; dfun_uses <- readIORef dfun_uses_var -- What dfuns are used
97 ; let used_names = allUses dus `unionNameSets` dfun_uses
98 ; usages <- mkUsageInfo hsc_env imports used_names
100 ; th_used <- readIORef th_var
102 pkgs | th_used = insertList thPackage (imp_dep_pkgs imports)
103 | otherwise = imp_dep_pkgs imports
105 deps = Deps { dep_mods = moduleEnvElts (imp_dep_mods imports),
106 dep_pkgs = sort pkgs,
107 dep_orphs = sort (imp_orphs imports) }
108 -- sort to get into canonical order
112 mg_exports = exports,
115 mg_dir_imps = [m | (m,_,_) <- moduleEnvElts (imp_mods imports)],
116 mg_rdr_env = rdr_env,
117 mg_fix_env = fix_env,
118 mg_deprecs = deprecs,
123 mg_foreign = ds_fords }
125 ; return (warns, Just mod_guts)
129 dflags = hsc_dflags hsc_env
130 ghci_mode = hsc_mode hsc_env
131 print_unqual = unQualInScope rdr_env
133 -- Desugarer warnings are SDocs; here we
134 -- add the info about whether or not to print unqualified
135 mk_warn :: (SrcSpan,SDoc) -> WarnMsg
136 mk_warn (loc, sdoc) = mkWarnMsg loc print_unqual sdoc
139 deSugarExpr :: HscEnv
140 -> Module -> GlobalRdrEnv -> TypeEnv
143 deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
144 = do { showPass dflags "Desugar"
145 ; us <- mkSplitUniqSupply 'd'
148 ; let { is_boot = emptyModuleEnv } -- Assume no hi-boot files when
149 -- doing stuff from the command line
150 ; (core_expr, ds_warns) <- initDs hsc_env this_mod type_env is_boot $
153 -- Display any warnings
154 -- Note: if -Werror is used, we don't signal an error here.
155 ; doIfSet (not (isEmptyBag ds_warns))
156 (printErrs (pprBagOfWarnings (mapBag mk_warn ds_warns)))
159 ; dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr core_expr)
164 dflags = hsc_dflags hsc_env
165 print_unqual = unQualInScope rdr_env
167 mk_warn :: (SrcSpan,SDoc) -> WarnMsg
168 mk_warn (loc,sdoc) = mkWarnMsg loc print_unqual sdoc
171 dsProgram ghci_mode (TcGblEnv { tcg_exports = exports,
172 tcg_keep = keep_alive,
176 = dsHsBinds auto_scc binds [] `thenDs` \ core_prs ->
177 dsForeigns fords `thenDs` \ (ds_fords, foreign_prs) ->
179 all_prs = foreign_prs ++ core_prs
180 local_bndrs = mkVarSet (map fst all_prs)
182 mappM (dsRule local_bndrs) rules `thenDs` \ ds_rules ->
184 final_prs = addExportFlags ghci_mode exports keep_alive
185 local_bndrs all_prs ds_rules
186 ds_binds = [Rec final_prs]
187 -- Notice that we put the whole lot in a big Rec, even the foreign binds
188 -- When compiling PrelFloat, which defines data Float = F# Float#
189 -- we want F# to be in scope in the foreign marshalling code!
190 -- You might think it doesn't matter, but the simplifier brings all top-level
191 -- things into the in-scope set before simplifying; so we get no unfolding for F#!
193 returnDs (ds_binds, ds_rules, ds_fords)
195 auto_scc | opt_SccProfilingOn = TopLevel
199 -- Set the no-discard flag if either
200 -- a) the Id is exported
201 -- b) it's mentioned in the RHS of an orphan rule
202 -- c) it's in the keep-alive set
204 -- It means that the binding won't be discarded EVEN if the binding
205 -- ends up being trivial (v = w) -- the simplifier would usually just
206 -- substitute w for v throughout, but we don't apply the substitution to
207 -- the rules (maybe we should?), so this substitution would make the rule
210 -- You might wonder why exported Ids aren't already marked as such;
211 -- it's just because the type checker is rather busy already and
212 -- I didn't want to pass in yet another mapping.
214 addExportFlags ghci_mode exports keep_alive bndrs prs rules
215 = [(add_export bndr, rhs) | (bndr,rhs) <- prs]
217 add_export bndr | dont_discard bndr = setIdLocalExported bndr
220 orph_rhs_fvs = unionVarSets [ ruleRhsFreeVars rule
221 | (id, rule) <- rules,
222 not (id `elemVarSet` bndrs) ]
223 -- An orphan rule must keep alive the free vars
224 -- of its right-hand side.
225 -- Non-orphan rules are attached to the Id (bndr_with_rules above)
226 -- and that keeps the rhs free vars alive
228 dont_discard bndr = is_exported name
229 || name `elemNameSet` keep_alive
230 || bndr `elemVarSet` orph_rhs_fvs
234 -- In interactive mode, we don't want to discard any top-level
235 -- entities at all (eg. do not inline them away during
236 -- simplification), and retain them all in the TypeEnv so they are
237 -- available from the command line.
239 -- isExternalName separates the user-defined top-level names from those
240 -- introduced by the type checker.
241 is_exported :: Name -> Bool
242 is_exported | ghci_mode == Interactive = isExternalName
243 | otherwise = (`elemNameSet` exports)
245 ppr_ds_rules [] = empty
247 = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
253 %************************************************************************
255 %* Desugaring transformation rules
257 %************************************************************************
260 dsRule :: IdSet -> LRuleDecl Id -> DsM (Id, CoreRule)
261 dsRule in_scope (L loc (HsRule name act vars lhs rhs))
263 ds_lhs all_vars lhs `thenDs` \ (fn, args) ->
264 dsLExpr rhs `thenDs` \ core_rhs ->
265 returnDs (fn, Rule name act tpl_vars args core_rhs)
267 tpl_vars = [var | RuleBndr (L _ var) <- vars]
268 all_vars = mkInScopeSet (extendVarSetList in_scope tpl_vars)
274 (HsLet [HsBindGroup dict_binds _ _] body) -> (dict_binds, body)
275 other -> (emptyBag, lhs)
277 mappM ds_dict_bind (bagToList dict_binds) `thenDs` \ dict_binds' ->
278 dsLExpr body `thenDs` \ body' ->
280 -- Substitute the dict bindings eagerly,
281 -- and take the body apart into a (f args) form
283 subst_env = mkSubstEnv [id | (id,rhs) <- dict_binds']
284 [ContEx subst_env rhs | (id,rhs) <- dict_binds']
285 -- Note recursion here... substitution won't terminate
286 -- if there is genuine recursion... which there isn't
288 subst = mkSubst all_vars subst_env
289 body'' = substExpr subst body'
292 -- Now unpack the resulting body
294 pair = case collectArgs body'' of
295 (Var fn, args) -> (fn, args)
296 other -> pprPanic "dsRule" (ppr lhs)
300 ds_dict_bind (L _ (VarBind id rhs)) =
301 dsLExpr rhs `thenDs` \ rhs' ->