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