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