[project @ 2003-10-30 09:03:15 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / Desugar.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[Desugar]{@deSugar@: the main function}
5
6 \begin{code}
7 module Desugar ( deSugar, deSugarExpr ) where
8
9 #include "HsVersions.h"
10
11 import CmdLineOpts      ( DynFlag(..), dopt, opt_SccProfilingOn )
12 import HscTypes         ( ModGuts(..), ModGuts, HscEnv(..), GhciMode(..),
13                           Dependencies(..), TypeEnv, 
14                           unQualInScope, availsToNameSet )
15 import HsSyn            ( MonoBinds, RuleDecl(..), RuleBndr(..), 
16                           HsExpr(..), HsBinds(..), MonoBinds(..) )
17 import TcHsSyn          ( TypecheckedRuleDecl, TypecheckedHsExpr )
18 import TcRnTypes        ( TcGblEnv(..), ImportAvails(..) )
19 import MkIface          ( mkUsageInfo )
20 import Id               ( Id, setIdLocalExported, idName )
21 import Name             ( Name, isExternalName )
22 import CoreSyn
23 import PprCore          ( pprIdRules, pprCoreExpr )
24 import Subst            ( substExpr, mkSubst, mkInScopeSet )
25 import DsMonad
26 import DsExpr           ( dsExpr )
27 import DsBinds          ( dsMonoBinds, 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, emptyModuleEnv )
32 import Id               ( Id )
33 import RdrName          ( GlobalRdrEnv )
34 import NameSet
35 import VarEnv
36 import VarSet
37 import Bag              ( isEmptyBag, mapBag, emptyBag )
38 import CoreLint         ( showPass, endPass )
39 import CoreFVs          ( ruleRhsFreeVars )
40 import ErrUtils         ( doIfSet, dumpIfSet_dyn, pprBagOfWarnings, 
41                           addShortWarnLocLine, errorsFound )
42 import Outputable
43 import qualified Pretty
44 import UniqSupply       ( mkSplitUniqSupply )
45 import SrcLoc           ( SrcLoc )
46 import DATA_IOREF       ( readIORef )
47 import FastString
48 \end{code}
49
50 %************************************************************************
51 %*                                                                      *
52 %*              The main function: deSugar
53 %*                                                                      *
54 %************************************************************************
55
56 \begin{code}
57 deSugar :: HscEnv -> TcGblEnv -> IO (Maybe ModGuts)
58 -- Can modify PCS by faulting in more declarations
59
60 deSugar hsc_env 
61         tcg_env@(TcGblEnv { tcg_mod       = mod,
62                             tcg_type_env  = type_env,
63                             tcg_imports   = imports,
64                             tcg_exports   = exports,
65                             tcg_dus       = dus, 
66                             tcg_inst_uses = dfun_uses_var,
67                             tcg_rdr_env   = rdr_env,
68                             tcg_fix_env   = fix_env,
69                             tcg_deprecs   = deprecs,
70                             tcg_insts     = insts })
71   = do  { showPass dflags "Desugar"
72
73         -- Do desugaring
74         ; let { is_boot = imp_dep_mods imports }
75         ; (results, warnings) <- initDs hsc_env mod type_env is_boot $
76                                  dsProgram ghci_mode tcg_env
77
78         ; let { (ds_binds, ds_rules, ds_fords) = results
79               ; warns    = mapBag mk_warn warnings
80               ; warn_doc = pprBagOfWarnings warns }
81
82         -- Display any warnings
83         ; doIfSet (not (isEmptyBag warnings))
84                   (printErrs warn_doc)
85
86         -- If warnings are considered errors, leave.
87         ; if errorsFound dflags (warns, emptyBag)
88            then return Nothing
89            else do
90
91         -- Lint result if necessary
92         { endPass dflags "Desugar" Opt_D_dump_ds ds_binds
93
94         -- Dump output
95         ; doIfSet (dopt Opt_D_dump_ds dflags) 
96                   (printDump (ppr_ds_rules ds_rules))
97
98         ; dfun_uses <- readIORef dfun_uses_var          -- What dfuns are used
99         ; let used_names = allUses dus `unionNameSets` dfun_uses
100         ; usages <- mkUsageInfo hsc_env imports used_names
101         ; let 
102              deps = Deps { dep_mods = moduleEnvElts (imp_dep_mods imports), 
103                            dep_pkgs = imp_dep_pkgs imports,
104                            dep_orphs = imp_orphs imports }
105              mod_guts = ModGuts {       
106                 mg_module   = mod,
107                 mg_exports  = exports,
108                 mg_deps     = deps,
109                 mg_usages   = usages,
110                 mg_dir_imps = [m | (m,_) <- moduleEnvElts (imp_mods imports)],
111                 mg_rdr_env  = rdr_env,
112                 mg_fix_env  = fix_env,
113                 mg_deprecs  = deprecs,
114                 mg_types    = type_env,
115                 mg_insts    = insts,
116                 mg_rules    = ds_rules,
117                 mg_binds    = ds_binds,
118                 mg_foreign  = ds_fords }
119         
120         ; return (Just mod_guts)
121         }}
122
123   where
124     dflags       = hsc_dflags hsc_env
125     ghci_mode    = hsc_mode hsc_env
126     print_unqual = unQualInScope rdr_env
127
128         -- Desugarer warnings are SDocs; here we
129         -- add the info about whether or not to print unqualified
130     mk_warn :: (SrcLoc,SDoc) -> (SrcLoc, Pretty.Doc)
131     mk_warn (loc, sdoc) = addShortWarnLocLine loc print_unqual sdoc
132
133
134 deSugarExpr :: HscEnv
135             -> Module -> GlobalRdrEnv -> TypeEnv 
136             -> TypecheckedHsExpr
137             -> IO CoreExpr
138 deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
139   = do  { showPass dflags "Desugar"
140         ; us <- mkSplitUniqSupply 'd'
141
142         -- Do desugaring
143         ; let { is_boot = emptyModuleEnv }      -- Assume no hi-boot files when
144                                                 -- doing stuff from the command line
145         ; (core_expr, ds_warns) <- initDs hsc_env this_mod type_env is_boot $
146                                    dsExpr tc_expr
147
148         -- Display any warnings 
149         -- Note: if -Werror is used, we don't signal an error here.
150         ; doIfSet (not (isEmptyBag ds_warns))
151                   (printErrs (pprBagOfWarnings (mapBag mk_warn ds_warns)))
152
153         -- Dump output
154         ; dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr core_expr)
155
156         ; return core_expr
157         }
158   where
159     dflags       = hsc_dflags hsc_env
160     print_unqual = unQualInScope rdr_env
161
162     mk_warn :: (SrcLoc,SDoc) -> (SrcLoc, Pretty.Doc)
163     mk_warn (loc,sdoc) = addShortWarnLocLine loc print_unqual sdoc
164
165
166 dsProgram ghci_mode (TcGblEnv { tcg_exports = exports,
167                                 tcg_keep    = keep_alive,
168                                 tcg_binds   = binds,
169                                 tcg_fords   = fords,
170                                 tcg_rules   = rules })
171   = dsMonoBinds auto_scc binds []       `thenDs` \ core_prs ->
172     dsForeigns fords                    `thenDs` \ (ds_fords, foreign_prs) ->
173     let
174         all_prs = foreign_prs ++ core_prs
175         local_bndrs = mkVarSet (map fst all_prs)
176     in
177     mappM (dsRule local_bndrs) rules    `thenDs` \ ds_rules ->
178     let
179         final_prs = addExportFlags ghci_mode exports keep_alive 
180                                    local_bndrs all_prs ds_rules
181         ds_binds  = [Rec final_prs]
182         -- Notice that we put the whole lot in a big Rec, even the foreign binds
183         -- When compiling PrelFloat, which defines data Float = F# Float#
184         -- we want F# to be in scope in the foreign marshalling code!
185         -- You might think it doesn't matter, but the simplifier brings all top-level
186         -- things into the in-scope set before simplifying; so we get no unfolding for F#!
187     in
188     returnDs (ds_binds, ds_rules, ds_fords)
189   where
190     auto_scc | opt_SccProfilingOn = TopLevel
191              | otherwise          = NoSccs
192
193 --              addExportFlags
194 -- Set the no-discard flag if either 
195 --      a) the Id is exported
196 --      b) it's mentioned in the RHS of an orphan rule
197 --      c) it's in the keep-alive set
198 --
199 -- It means that the binding won't be discarded EVEN if the binding
200 -- ends up being trivial (v = w) -- the simplifier would usually just 
201 -- substitute w for v throughout, but we don't apply the substitution to
202 -- the rules (maybe we should?), so this substitution would make the rule
203 -- bogus.
204
205 -- You might wonder why exported Ids aren't already marked as such;
206 -- it's just because the type checker is rather busy already and
207 -- I didn't want to pass in yet another mapping.
208
209 addExportFlags ghci_mode exports keep_alive bndrs prs rules
210   = [(add_export bndr, rhs) | (bndr,rhs) <- prs]
211   where
212     add_export bndr | dont_discard bndr = setIdLocalExported bndr
213                     | otherwise         = bndr
214
215     orph_rhs_fvs = unionVarSets [ ruleRhsFreeVars rule
216                                 | (id, rule) <- rules, 
217                                   not (id `elemVarSet` bndrs) ]
218         -- An orphan rule must keep alive the free vars 
219         -- of its right-hand side.  
220         -- Non-orphan rules are attached to the Id (bndr_with_rules above)
221         -- and that keeps the rhs free vars alive
222
223     dont_discard bndr = is_exported name
224                      || name `elemNameSet` keep_alive
225                      || bndr `elemVarSet` orph_rhs_fvs 
226                      where
227                         name = idName bndr
228
229         -- In interactive mode, we don't want to discard any top-level
230         -- entities at all (eg. do not inline them away during
231         -- simplification), and retain them all in the TypeEnv so they are
232         -- available from the command line.
233         --
234         -- isExternalName separates the user-defined top-level names from those
235         -- introduced by the type checker.
236     is_exported :: Name -> Bool
237     is_exported | ghci_mode == Interactive = isExternalName
238                 | otherwise                = (`elemNameSet` export_fvs)
239
240     export_fvs = availsToNameSet exports
241
242 ppr_ds_rules [] = empty
243 ppr_ds_rules rules
244   = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
245     pprIdRules rules
246 \end{code}
247
248
249
250 %************************************************************************
251 %*                                                                      *
252 %*              Desugaring transformation rules
253 %*                                                                      *
254 %************************************************************************
255
256 \begin{code}
257 dsRule :: IdSet -> TypecheckedRuleDecl -> DsM (Id, CoreRule)
258 dsRule in_scope (HsRule name act vars lhs rhs loc)
259   = putSrcLocDs loc             $
260     ds_lhs all_vars lhs         `thenDs` \ (fn, args) ->
261     dsExpr rhs                  `thenDs` \ core_rhs ->
262     returnDs (fn, Rule name act tpl_vars args core_rhs)
263   where
264     tpl_vars = [var | RuleBndr var <- vars]
265     all_vars = mkInScopeSet (in_scope `unionVarSet` mkVarSet tpl_vars)
266
267 ds_lhs all_vars lhs
268   = let
269         (dict_binds, body) = case lhs of
270                 (HsLet (MonoBind dict_binds _ _) body) -> (dict_binds, body)
271                 other                                  -> (EmptyMonoBinds, lhs)
272     in
273     ds_dict_binds dict_binds    `thenDs` \ dict_binds' ->
274     dsExpr body                 `thenDs` \ body' ->
275
276         -- Substitute the dict bindings eagerly,
277         -- and take the body apart into a (f args) form
278     let
279         subst_env = mkSubstEnv [id                   | (id,rhs) <- dict_binds']
280                                [ContEx subst_env rhs | (id,rhs) <- dict_binds']
281                         -- Note recursion here... substitution won't terminate
282                         -- if there is genuine recursion... which there isn't
283
284         subst = mkSubst all_vars subst_env
285         body'' = substExpr subst body'
286     in
287         
288         -- Now unpack the resulting body
289     let
290         pair = case collectArgs body'' of
291                         (Var fn, args) -> (fn, args)
292                         other          -> pprPanic "dsRule" (ppr lhs)
293     in
294     returnDs pair
295
296 ds_dict_binds EmptyMonoBinds       = returnDs []
297 ds_dict_binds (AndMonoBinds b1 b2) = ds_dict_binds b1   `thenDs` \ env1 ->
298                                      ds_dict_binds b2   `thenDs` \ env2 ->
299                                      returnDs (env1 ++ env2)
300 ds_dict_binds (VarMonoBind id rhs) = dsExpr rhs         `thenDs` \ rhs' ->
301                                      returnDs [(id,rhs')]
302 \end{code}