29801f28cdefc3b5343eb4600b68f29ccb71b6cb
[ghc-hetmet.git] / 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                           opt_AutoSccsOnAllToplevs,
14                           opt_AutoSccsOnExportedToplevs )
15 import DriverPhases     ( isHsBoot )
16 import HscTypes         ( ModGuts(..), HscEnv(..), availsToNameSet,
17                           Dependencies(..), ForeignStubs(..), TypeEnv, IsBootInterface )
18 import HsSyn            ( RuleDecl(..), RuleBndr(..), LHsExpr, LRuleDecl )
19 import TcRnTypes        ( TcGblEnv(..), ImportAvails(..) )
20 import MkIface          ( mkUsageInfo )
21 import Id               ( Id, setIdExported, idName )
22 import Name             ( Name, isExternalName, nameIsLocalOrFrom, nameOccName )
23 import CoreSyn
24 import PprCore          ( pprRules, pprCoreExpr )
25 import DsMonad
26 import DsExpr           ( dsLExpr )
27 import DsBinds          ( dsTopLHsBinds, decomposeRuleLhs, AutoScc(..) )
28 import DsForeign        ( dsForeigns )
29 import DsExpr           ()      -- Forces DsExpr to be compiled; DsBinds only
30                                 -- depends on DsExpr.hi-boot.
31 import Module
32 import UniqFM           ( eltsUFM, delFromUFM )
33 import PackageConfig    ( thPackageId )
34 import RdrName          ( GlobalRdrEnv )
35 import NameSet
36 import VarSet
37 import Rules            ( roughTopNames )
38 import CoreLint         ( showPass, endPass )
39 import CoreFVs          ( ruleRhsFreeVars, exprsFreeNames )
40 import ErrUtils         ( doIfSet, dumpIfSet_dyn )
41 import ListSetOps       ( insertList )
42 import Outputable
43 import SrcLoc           ( Located(..) )
44 import DATA_IOREF       ( readIORef )
45 import Maybes           ( catMaybes )
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 (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_src       = hsc_src,
63                             tcg_type_env  = type_env,
64                             tcg_imports   = imports,
65                             tcg_exports   = exports,
66                             tcg_dus       = dus, 
67                             tcg_inst_uses = dfun_uses_var,
68                             tcg_th_used   = th_var,
69                             tcg_keep      = keep_var,
70                             tcg_rdr_env   = rdr_env,
71                             tcg_fix_env   = fix_env,
72                             tcg_deprecs   = deprecs,
73                             tcg_binds     = binds,
74                             tcg_fords     = fords,
75                             tcg_rules     = rules,
76                             tcg_insts     = insts,
77                             tcg_fam_insts = fam_insts })
78   = do  { showPass dflags "Desugar"
79
80         -- Desugar the program
81         ; let export_set = availsToNameSet exports
82         ; let auto_scc = mkAutoScc mod export_set
83
84         ; mb_res <- case ghcMode dflags of
85                      JustTypecheck -> return (Just ([], [], NoStubs))
86                      _             -> initDs hsc_env mod rdr_env type_env $ do
87                                         { core_prs <- dsTopLHsBinds auto_scc binds
88                                         ; (ds_fords, foreign_prs) <- dsForeigns fords
89                                         ; let all_prs = foreign_prs ++ core_prs
90                                               local_bndrs = mkVarSet (map fst all_prs)
91                                         ; ds_rules <- mappM (dsRule mod local_bndrs) rules
92                                         ; return (all_prs, catMaybes ds_rules, ds_fords)
93                                         }
94         ; case mb_res of {
95            Nothing -> return Nothing ;
96            Just (all_prs, ds_rules, ds_fords) -> do
97
98         {       -- Add export flags to bindings
99           keep_alive <- readIORef keep_var
100         ; let final_prs = addExportFlags ghci_mode export_set
101                                  keep_alive 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               pkgs | th_used   = insertList thPackageId (imp_dep_pkgs imports)
120                    | otherwise = imp_dep_pkgs imports
121
122               dep_mods = eltsUFM (delFromUFM (imp_dep_mods imports) (moduleName mod))
123                 -- M.hi-boot can be in the imp_dep_mods, but we must remove
124                 -- it before recording the modules on which this one depends!
125                 -- (We want to retain M.hi-boot in imp_dep_mods so that 
126                 --  loadHiBootInterface can see if M's direct imports depend 
127                 --  on M.hi-boot, and hence that we should do the hi-boot consistency 
128                 --  check.)
129
130               dir_imp_mods = imp_mods imports
131
132         ; usages <- mkUsageInfo hsc_env dir_imp_mods dep_mods used_names
133
134         ; let 
135                 -- Modules don't compare lexicographically usually, 
136                 -- but we want them to do so here.
137              le_mod :: Module -> Module -> Bool  
138              le_mod m1 m2 = moduleNameFS (moduleName m1) 
139                                 <= moduleNameFS (moduleName m2)
140              le_dep_mod :: (ModuleName, IsBootInterface) -> (ModuleName, IsBootInterface) -> Bool        
141              le_dep_mod (m1,_) (m2,_) = moduleNameFS m1 <= moduleNameFS m2
142
143              deps = Deps { dep_mods  = sortLe le_dep_mod dep_mods,
144                            dep_pkgs  = sortLe (<=)   pkgs,      
145                            dep_orphs = sortLe le_mod (imp_orphs imports) }
146                 -- sort to get into canonical order
147
148              mod_guts = ModGuts {       
149                 mg_module    = mod,
150                 mg_boot      = isHsBoot hsc_src,
151                 mg_exports   = exports,
152                 mg_deps      = deps,
153                 mg_usages    = usages,
154                 mg_dir_imps  = [m | (m,_,_) <- moduleEnvElts dir_imp_mods],
155                 mg_rdr_env   = rdr_env,
156                 mg_fix_env   = fix_env,
157                 mg_deprecs   = deprecs,
158                 mg_types     = type_env,
159                 mg_insts     = insts,
160                 mg_fam_insts = fam_insts,
161                 mg_rules     = ds_rules,
162                 mg_binds     = ds_binds,
163                 mg_foreign   = ds_fords }
164         
165         ; return (Just mod_guts)
166         }}}
167
168   where
169     dflags    = hsc_dflags hsc_env
170     ghci_mode = ghcMode (hsc_dflags hsc_env)
171
172 mkAutoScc :: Module -> NameSet -> AutoScc
173 mkAutoScc mod exports
174   | not opt_SccProfilingOn      -- No profiling
175   = NoSccs              
176   | opt_AutoSccsOnAllToplevs    -- Add auto-scc on all top-level things
177   = AddSccs mod (\id -> True)
178   | opt_AutoSccsOnExportedToplevs       -- Only on exported things
179   = AddSccs mod (\id -> idName id `elemNameSet` exports)
180   | otherwise
181   = NoSccs
182
183
184 deSugarExpr :: HscEnv
185             -> Module -> GlobalRdrEnv -> TypeEnv 
186             -> LHsExpr Id
187             -> IO (Maybe CoreExpr)
188 -- Prints its own errors; returns Nothing if error occurred
189
190 deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
191   = do  { let dflags = hsc_dflags hsc_env
192         ; showPass dflags "Desugar"
193
194         -- Do desugaring
195         ; mb_core_expr <- initDs hsc_env this_mod rdr_env type_env $
196                           dsLExpr tc_expr
197
198         ; case mb_core_expr of {
199             Nothing   -> return Nothing ;
200             Just expr -> do {
201
202                 -- Dump output
203           dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr expr)
204
205         ; return (Just expr) } } }
206
207 --              addExportFlags
208 -- Set the no-discard flag if either 
209 --      a) the Id is exported
210 --      b) it's mentioned in the RHS of an orphan rule
211 --      c) it's in the keep-alive set
212 --
213 -- It means that the binding won't be discarded EVEN if the binding
214 -- ends up being trivial (v = w) -- the simplifier would usually just 
215 -- substitute w for v throughout, but we don't apply the substitution to
216 -- the rules (maybe we should?), so this substitution would make the rule
217 -- bogus.
218
219 -- You might wonder why exported Ids aren't already marked as such;
220 -- it's just because the type checker is rather busy already and
221 -- I didn't want to pass in yet another mapping.
222
223 addExportFlags ghci_mode exports keep_alive prs rules
224   = [(add_export bndr, rhs) | (bndr,rhs) <- prs]
225   where
226     add_export bndr
227         | dont_discard bndr = setIdExported bndr
228         | otherwise         = bndr
229
230     orph_rhs_fvs = unionVarSets [ ruleRhsFreeVars rule
231                                 | rule <- rules, 
232                                   not (isLocalRule rule) ]
233         -- A non-local rule keeps alive the free vars of its right-hand side. 
234         -- (A "non-local" is one whose head function is not locally defined.)
235         -- Local rules are (later, after gentle simplification) 
236         -- attached to the Id, and that keeps the rhs free vars alive.
237
238     dont_discard bndr = is_exported name
239                      || name `elemNameSet` keep_alive
240                      || bndr `elemVarSet` orph_rhs_fvs 
241                      where
242                         name = idName bndr
243
244         -- In interactive mode, we don't want to discard any top-level
245         -- entities at all (eg. do not inline them away during
246         -- simplification), and retain them all in the TypeEnv so they are
247         -- available from the command line.
248         --
249         -- isExternalName separates the user-defined top-level names from those
250         -- introduced by the type checker.
251     is_exported :: Name -> Bool
252     is_exported | ghci_mode == Interactive = isExternalName
253                 | otherwise                = (`elemNameSet` exports)
254
255 ppr_ds_rules [] = empty
256 ppr_ds_rules rules
257   = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
258     pprRules rules
259 \end{code}
260
261
262
263 %************************************************************************
264 %*                                                                      *
265 %*              Desugaring transformation rules
266 %*                                                                      *
267 %************************************************************************
268
269 \begin{code}
270 dsRule :: Module -> IdSet -> LRuleDecl Id -> DsM (Maybe CoreRule)
271 dsRule mod in_scope (L loc (HsRule name act vars lhs tv_lhs rhs fv_rhs))
272   = putSrcSpanDs loc $ 
273     do  { let bndrs     = [var | RuleBndr (L _ var) <- vars]
274         ; lhs'  <- dsLExpr lhs
275         ; rhs'  <- dsLExpr rhs
276
277         ; case decomposeRuleLhs bndrs lhs' of {
278                 Nothing -> do { warnDs msg; return Nothing } ;
279                 Just (bndrs', fn_id, args) -> do
280         
281         -- Substitute the dict bindings eagerly,
282         -- and take the body apart into a (f args) form
283         { let local_rule = nameIsLocalOrFrom mod fn_name
284                 -- NB we can't use isLocalId in the orphan test, 
285                 -- because isLocalId isn't true of class methods
286               fn_name   = idName fn_id
287               lhs_names = fn_name : nameSetToList (exprsFreeNames args)
288                 -- No need to delete bndrs, because
289                 -- exprsFreeNames finds only External names
290
291                 -- A rule is an orphan only if none of the variables
292                 -- mentioned on its left-hand side are locally defined
293               orph = case filter (nameIsLocalOrFrom mod) lhs_names of
294                         (n:ns) -> Just (nameOccName n)
295                         []     -> Nothing
296
297               rule = Rule { ru_name = name, ru_fn = fn_name, ru_act = act,
298                             ru_bndrs = bndrs', ru_args = args, ru_rhs = rhs', 
299                             ru_rough = roughTopNames args, 
300                             ru_local = local_rule, ru_orph = orph }
301         ; return (Just rule)
302         } } }
303   where
304     msg = hang (ptext SLIT("RULE left-hand side too complicated to desugar; ignored"))
305              2 (ppr lhs)
306 \end{code}