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