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