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