[project @ 2005-05-19 11:15:40 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 DynFlags         ( DynFlag(..), DynFlags(..), dopt, GhcMode(..) )
12 import StaticFlags      ( opt_SccProfilingOn )
13 import DriverPhases     ( isHsBoot )
14 import HscTypes         ( 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 RdrName          ( GlobalRdrEnv )
33 import NameSet
34 import VarEnv
35 import VarSet
36 import Bag              ( Bag, isEmptyBag, emptyBag, bagToList )
37 import Rules            ( roughTopNames )
38 import CoreLint         ( showPass, endPass )
39 import CoreFVs          ( ruleRhsFreeVars, exprsFreeNames )
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                                 | rule <- rules, 
226                                   not (isLocalRule rule) ]
227         -- A non-local rule keeps alive the free vars of its right-hand side. 
228         -- (A "non-local" is one whose head function is not locally defined.)
229         -- Local rules are (later, after gentle simplification) 
230         -- attached to the Id, and that keeps the rhs free vars alive.
231
232     dont_discard bndr = is_exported name
233                      || name `elemNameSet` keep_alive
234                      || bndr `elemVarSet` orph_rhs_fvs 
235                      where
236                         name = idName bndr
237
238         -- In interactive mode, we don't want to discard any top-level
239         -- entities at all (eg. do not inline them away during
240         -- simplification), and retain them all in the TypeEnv so they are
241         -- available from the command line.
242         --
243         -- isExternalName separates the user-defined top-level names from those
244         -- introduced by the type checker.
245     is_exported :: Name -> Bool
246     is_exported | ghci_mode == Interactive = isExternalName
247                 | otherwise                = (`elemNameSet` exports)
248
249 ppr_ds_rules [] = empty
250 ppr_ds_rules rules
251   = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
252     pprRules rules
253 \end{code}
254
255
256
257 %************************************************************************
258 %*                                                                      *
259 %*              Desugaring transformation rules
260 %*                                                                      *
261 %************************************************************************
262
263 \begin{code}
264 dsRule :: Module -> IdSet -> LRuleDecl Id -> DsM CoreRule
265 dsRule mod in_scope (L loc (HsRule name act vars lhs rhs))
266   = putSrcSpanDs loc $ 
267     do  { let (dict_binds, body)
268                 = case unLoc lhs of
269                     (HsLet [HsBindGroup dbs _ _] body) -> (dbs, body)
270                     other                              -> (emptyBag, lhs)
271
272               ds_dict_bind (L _ (VarBind id rhs))
273                   = do  { rhs' <- dsLExpr rhs ; returnDs (id,rhs') }
274
275         ; dict_binds' <- mappM ds_dict_bind (bagToList dict_binds)
276         ; body'       <- dsLExpr body
277         ; rhs'        <- dsLExpr rhs
278
279         -- Substitute the dict bindings eagerly,
280         -- and take the body apart into a (f args) form
281         ; let bndrs     = [var | RuleBndr (L _ var) <- vars]
282               in_scope' = mkInScopeSet (extendVarSetList in_scope bndrs)
283               subst     = mkSubst in_scope' emptyVarEnv (mkVarEnv id_pairs)
284               id_pairs  = [(id, substExpr subst rhs) | (id,rhs) <- dict_binds']
285                         -- Note recursion here... substitution won't terminate
286                         -- if there is genuine recursion... which there isn't
287
288               body'' = substExpr subst body'
289
290               (fn, args) = case collectArgs body'' of
291                                 (Var fn_id, args) -> (idName fn_id, args)
292                                 other -> pprPanic "dsRule" (ppr lhs) 
293
294               local_rule = nameIsLocalOrFrom mod fn
295                 -- NB we can't use isLocalId in the orphan test, 
296                 -- because isLocalId isn't true of class methods
297               lhs_names = fn : nameSetToList (exprsFreeNames args)
298                 -- No need to delete bndrs, because
299                 -- exprsFreeNams finds only External names
300               orph = case filter (nameIsLocalOrFrom mod) lhs_names of
301                         (n:ns) -> Just (nameOccName n)
302                         []     -> Nothing
303
304         ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
305                          ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs', 
306                          ru_rough = roughTopNames args, 
307                          ru_local = local_rule, ru_orph = orph })
308         }
309 \end{code}