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