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