Generalise Package Support
[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 Bag              ( Bag, isEmptyBag, emptyBag )
36 import Rules            ( roughTopNames )
37 import CoreLint         ( showPass, endPass )
38 import CoreFVs          ( ruleRhsFreeVars, exprsFreeNames )
39 import ErrUtils         ( doIfSet, dumpIfSet_dyn, printBagOfWarnings, 
40                           errorsFound, WarnMsg )
41 import ListSetOps       ( insertList )
42 import Outputable
43 import UniqSupply       ( mkSplitUniqSupply )
44 import SrcLoc           ( Located(..) )
45 import DATA_IOREF       ( readIORef )
46 import Maybes           ( catMaybes )
47 import FastString
48 import Util             ( sortLe )
49 \end{code}
50
51 %************************************************************************
52 %*                                                                      *
53 %*              The main function: deSugar
54 %*                                                                      *
55 %************************************************************************
56
57 \begin{code}
58 deSugar :: HscEnv -> TcGblEnv -> IO (Bag WarnMsg, Maybe ModGuts)
59 -- Can modify PCS by faulting in more declarations
60
61 deSugar hsc_env 
62         tcg_env@(TcGblEnv { tcg_mod       = mod,
63                             tcg_src       = hsc_src,
64                             tcg_type_env  = type_env,
65                             tcg_imports   = imports,
66                             tcg_exports   = exports,
67                             tcg_dus       = dus, 
68                             tcg_inst_uses = dfun_uses_var,
69                             tcg_th_used   = th_var,
70                             tcg_keep      = keep_var,
71                             tcg_rdr_env   = rdr_env,
72                             tcg_fix_env   = fix_env,
73                             tcg_deprecs   = deprecs,
74                             tcg_binds     = binds,
75                             tcg_fords     = fords,
76                             tcg_rules     = rules,
77                             tcg_insts     = insts })
78   = do  { showPass dflags "Desugar"
79
80         -- Desugar the program
81         ; ((all_prs, ds_rules, ds_fords), warns) 
82                 <- case ghcMode (hsc_dflags hsc_env) of
83                      JustTypecheck -> return (([], [], NoStubs), emptyBag)
84                      _             -> initDs hsc_env mod rdr_env type_env $ do
85                                         { core_prs <- dsTopLHsBinds 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, catMaybes ds_rules, ds_fords)
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               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         ; showPass dflags "Desugar 3"
133
134         ; usages <- mkUsageInfo hsc_env dir_imp_mods dep_mods used_names
135
136         ; showPass dflags "Desugar 4"
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 = moduleNameFS (moduleName m1) 
143                                 <= moduleNameFS (moduleName m2)
144              le_dep_mod :: (ModuleName, IsBootInterface) -> (ModuleName, IsBootInterface) -> Bool        
145              le_dep_mod (m1,_) (m2,_) = moduleNameFS m1 <= moduleNameFS m2
146
147              deps = Deps { dep_mods  = sortLe le_dep_mod dep_mods,
148                            dep_pkgs  = sortLe (<=)   pkgs,      
149                            dep_orphs = sortLe le_mod (imp_orphs imports) }
150                 -- sort to get into canonical order
151
152              mod_guts = ModGuts {       
153                 mg_module   = mod,
154                 mg_boot     = isHsBoot hsc_src,
155                 mg_exports  = exports,
156                 mg_deps     = deps,
157                 mg_usages   = usages,
158                 mg_dir_imps = [m | (m,_,_) <- moduleEnvElts dir_imp_mods],
159                 mg_rdr_env  = rdr_env,
160                 mg_fix_env  = fix_env,
161                 mg_deprecs  = deprecs,
162                 mg_types    = type_env,
163                 mg_insts    = insts,
164                 mg_rules    = ds_rules,
165                 mg_binds    = ds_binds,
166                 mg_foreign  = ds_fords }
167         
168         ; return (warns, Just mod_guts)
169         }}
170
171   where
172     dflags       = hsc_dflags hsc_env
173     ghci_mode    = ghcMode (hsc_dflags hsc_env)
174     auto_scc | opt_SccProfilingOn = TopLevel
175              | otherwise          = NoSccs
176
177 deSugarExpr :: HscEnv
178             -> Module -> GlobalRdrEnv -> TypeEnv 
179             -> LHsExpr Id
180             -> IO CoreExpr
181 deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
182   = do  { showPass dflags "Desugar"
183         ; us <- mkSplitUniqSupply 'd'
184
185         -- Do desugaring
186         ; (core_expr, ds_warns) <- initDs hsc_env this_mod rdr_env type_env $
187                                    dsLExpr tc_expr
188
189         -- Display any warnings 
190         -- Note: if -Werror is used, we don't signal an error here.
191         ; doIfSet (not (isEmptyBag ds_warns))
192                   (printBagOfWarnings dflags ds_warns)
193
194         -- Dump output
195         ; dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr core_expr)
196
197         ; return core_expr
198         }
199   where
200     dflags       = hsc_dflags hsc_env
201
202
203 --              addExportFlags
204 -- Set the no-discard flag if either 
205 --      a) the Id is exported
206 --      b) it's mentioned in the RHS of an orphan rule
207 --      c) it's in the keep-alive set
208 --
209 -- It means that the binding won't be discarded EVEN if the binding
210 -- ends up being trivial (v = w) -- the simplifier would usually just 
211 -- substitute w for v throughout, but we don't apply the substitution to
212 -- the rules (maybe we should?), so this substitution would make the rule
213 -- bogus.
214
215 -- You might wonder why exported Ids aren't already marked as such;
216 -- it's just because the type checker is rather busy already and
217 -- I didn't want to pass in yet another mapping.
218
219 addExportFlags ghci_mode exports keep_alive prs rules
220   = [(add_export bndr, rhs) | (bndr,rhs) <- prs]
221   where
222     add_export bndr
223         | dont_discard bndr = setIdExported bndr
224         | otherwise         = bndr
225
226     orph_rhs_fvs = unionVarSets [ ruleRhsFreeVars rule
227                                 | rule <- rules, 
228                                   not (isLocalRule rule) ]
229         -- A non-local rule keeps alive the free vars of its right-hand side. 
230         -- (A "non-local" is one whose head function is not locally defined.)
231         -- Local rules are (later, after gentle simplification) 
232         -- attached to the Id, and that keeps the rhs free vars alive.
233
234     dont_discard bndr = is_exported name
235                      || name `elemNameSet` keep_alive
236                      || bndr `elemVarSet` orph_rhs_fvs 
237                      where
238                         name = idName bndr
239
240         -- In interactive mode, we don't want to discard any top-level
241         -- entities at all (eg. do not inline them away during
242         -- simplification), and retain them all in the TypeEnv so they are
243         -- available from the command line.
244         --
245         -- isExternalName separates the user-defined top-level names from those
246         -- introduced by the type checker.
247     is_exported :: Name -> Bool
248     is_exported | ghci_mode == Interactive = isExternalName
249                 | otherwise                = (`elemNameSet` exports)
250
251 ppr_ds_rules [] = empty
252 ppr_ds_rules rules
253   = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
254     pprRules rules
255 \end{code}
256
257
258
259 %************************************************************************
260 %*                                                                      *
261 %*              Desugaring transformation rules
262 %*                                                                      *
263 %************************************************************************
264
265 \begin{code}
266 dsRule :: Module -> IdSet -> LRuleDecl Id -> DsM (Maybe CoreRule)
267 dsRule mod in_scope (L loc (HsRule name act vars lhs tv_lhs rhs fv_rhs))
268   = putSrcSpanDs loc $ 
269     do  { let bndrs     = [var | RuleBndr (L _ var) <- vars]
270         ; lhs'  <- dsLExpr lhs
271         ; rhs'  <- dsLExpr rhs
272
273         ; case decomposeRuleLhs bndrs lhs' of {
274                 Nothing -> do { dsWarn msg; return Nothing } ;
275                 Just (bndrs', fn_id, args) -> do
276         
277         -- Substitute the dict bindings eagerly,
278         -- and take the body apart into a (f args) form
279         { let local_rule = nameIsLocalOrFrom mod fn_name
280                 -- NB we can't use isLocalId in the orphan test, 
281                 -- because isLocalId isn't true of class methods
282               fn_name   = idName fn_id
283               lhs_names = fn_name : nameSetToList (exprsFreeNames args)
284                 -- No need to delete bndrs, because
285                 -- exprsFreeNames finds only External names
286               orph = case filter (nameIsLocalOrFrom mod) lhs_names of
287                         (n:ns) -> Just (nameOccName n)
288                         []     -> Nothing
289
290               rule = Rule { ru_name = name, ru_fn = fn_name, ru_act = act,
291                             ru_bndrs = bndrs', ru_args = args, ru_rhs = rhs', 
292                             ru_rough = roughTopNames args, 
293                             ru_local = local_rule, ru_orph = orph }
294         ; return (Just rule)
295         } } }
296   where
297     msg = hang (ptext SLIT("RULE left-hand side too complicated to desugar; ignored"))
298              2 (ppr lhs)
299 \end{code}