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