02c475fd6be4842fcc934930f87a6227d95e4f39
[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, 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, moduleEnvElts )
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 Data.List        ( sort )
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              deps = Deps { dep_mods = moduleEnvElts (imp_dep_mods imports), 
104                            dep_pkgs  = sort pkgs,       
105                            dep_orphs = sort (imp_orphs imports) }
106                 -- sort to get into canonical order
107
108              mod_guts = ModGuts {       
109                 mg_module   = mod,
110                 mg_exports  = exports,
111                 mg_deps     = deps,
112                 mg_usages   = usages,
113                 mg_dir_imps = [m | (m,_,_) <- moduleEnvElts (imp_mods imports)],
114                 mg_rdr_env  = rdr_env,
115                 mg_fix_env  = fix_env,
116                 mg_deprecs  = deprecs,
117                 mg_types    = type_env,
118                 mg_insts    = insts,
119                 mg_rules    = ds_rules,
120                 mg_binds    = ds_binds,
121                 mg_foreign  = ds_fords }
122         
123         ; return (warns, Just mod_guts)
124         }}
125
126   where
127     dflags       = hsc_dflags hsc_env
128     ghci_mode    = hsc_mode hsc_env
129     print_unqual = unQualInScope rdr_env
130
131         -- Desugarer warnings are SDocs; here we
132         -- add the info about whether or not to print unqualified
133     mk_warn :: (SrcSpan,SDoc) -> WarnMsg
134     mk_warn (loc, sdoc) = mkWarnMsg loc print_unqual sdoc
135
136
137 deSugarExpr :: HscEnv
138             -> Module -> GlobalRdrEnv -> TypeEnv 
139             -> LHsExpr Id
140             -> IO CoreExpr
141 deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
142   = do  { showPass dflags "Desugar"
143         ; us <- mkSplitUniqSupply 'd'
144
145         -- Do desugaring
146         ; (core_expr, ds_warns) <- initDs hsc_env this_mod type_env $
147                                    dsLExpr tc_expr
148
149         -- Display any warnings 
150         -- Note: if -Werror is used, we don't signal an error here.
151         ; doIfSet (not (isEmptyBag ds_warns))
152                   (printErrs (pprBagOfWarnings (mapBag mk_warn ds_warns)))
153
154         -- Dump output
155         ; dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr core_expr)
156
157         ; return core_expr
158         }
159   where
160     dflags       = hsc_dflags hsc_env
161     print_unqual = unQualInScope rdr_env
162
163     mk_warn :: (SrcSpan,SDoc) -> WarnMsg
164     mk_warn (loc,sdoc) = mkWarnMsg loc print_unqual sdoc
165
166
167 dsProgram ghci_mode (TcGblEnv { tcg_exports = exports,
168                                 tcg_keep    = keep_alive,
169                                 tcg_binds   = binds,
170                                 tcg_fords   = fords,
171                                 tcg_rules   = rules })
172   = dsHsBinds auto_scc binds [] `thenDs` \ core_prs ->
173     dsForeigns fords                    `thenDs` \ (ds_fords, foreign_prs) ->
174     let
175         all_prs = foreign_prs ++ core_prs
176         local_bndrs = mkVarSet (map fst all_prs)
177     in
178     mappM (dsRule local_bndrs) rules    `thenDs` \ ds_rules ->
179     let
180         final_prs = addExportFlags ghci_mode exports keep_alive 
181                                    local_bndrs all_prs ds_rules
182         ds_binds  = [Rec final_prs]
183         -- Notice that we put the whole lot in a big Rec, even the foreign binds
184         -- When compiling PrelFloat, which defines data Float = F# Float#
185         -- we want F# to be in scope in the foreign marshalling code!
186         -- You might think it doesn't matter, but the simplifier brings all top-level
187         -- things into the in-scope set before simplifying; so we get no unfolding for F#!
188     in
189     returnDs (ds_binds, ds_rules, ds_fords)
190   where
191     auto_scc | opt_SccProfilingOn = TopLevel
192              | otherwise          = NoSccs
193
194 --              addExportFlags
195 -- Set the no-discard flag if either 
196 --      a) the Id is exported
197 --      b) it's mentioned in the RHS of an orphan rule
198 --      c) it's in the keep-alive set
199 --
200 -- It means that the binding won't be discarded EVEN if the binding
201 -- ends up being trivial (v = w) -- the simplifier would usually just 
202 -- substitute w for v throughout, but we don't apply the substitution to
203 -- the rules (maybe we should?), so this substitution would make the rule
204 -- bogus.
205
206 -- You might wonder why exported Ids aren't already marked as such;
207 -- it's just because the type checker is rather busy already and
208 -- I didn't want to pass in yet another mapping.
209
210 addExportFlags ghci_mode exports keep_alive bndrs prs rules
211   = [(add_export bndr, rhs) | (bndr,rhs) <- prs]
212   where
213     add_export bndr | dont_discard bndr = setIdLocalExported bndr
214                     | otherwise         = bndr
215
216     orph_rhs_fvs = unionVarSets [ ruleRhsFreeVars rule
217                                 | (id, rule) <- rules, 
218                                   not (id `elemVarSet` bndrs) ]
219         -- An orphan rule must keep alive the free vars 
220         -- of its right-hand side.  
221         -- Non-orphan rules are attached to the Id (bndr_with_rules above)
222         -- and that keeps the rhs free vars alive
223
224     dont_discard bndr = is_exported name
225                      || name `elemNameSet` keep_alive
226                      || bndr `elemVarSet` orph_rhs_fvs 
227                      where
228                         name = idName bndr
229
230         -- In interactive mode, we don't want to discard any top-level
231         -- entities at all (eg. do not inline them away during
232         -- simplification), and retain them all in the TypeEnv so they are
233         -- available from the command line.
234         --
235         -- isExternalName separates the user-defined top-level names from those
236         -- introduced by the type checker.
237     is_exported :: Name -> Bool
238     is_exported | ghci_mode == Interactive = isExternalName
239                 | otherwise                = (`elemNameSet` 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 = extendIdSubstList (mkSubst all_vars) pairs
280         pairs = [(id, ContEx subst rhs) | (id,rhs) <- dict_binds']
281                         -- Note recursion here... substitution won't terminate
282                         -- if there is genuine recursion... which there isn't
283         body'' = substExpr subst body'
284     in
285         
286         -- Now unpack the resulting body
287     let
288         pair = case collectArgs body'' of
289                         (Var fn, args) -> (fn, args)
290                         other          -> pprPanic "dsRule" (ppr lhs)
291     in
292     returnDs pair
293
294 ds_dict_bind (L _ (VarBind id rhs)) =
295   dsLExpr rhs `thenDs` \ rhs' ->
296   returnDs (id,rhs')
297 \end{code}