e7ae7ee9935c3a6b8e78b8a7207d3eae5db7e5a6
[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 CmdLineOpts      ( DynFlag(..), dopt, opt_SccProfilingOn )
12 import HscTypes         ( ModGuts(..), ModGuts, HscEnv(..), GhciMode(..),
13                           Dependencies(..), TypeEnv, IsBootInterface, unQualInScope )
14 import HsSyn            ( RuleDecl(..), RuleBndr(..), HsExpr(..), LHsExpr,
15                           HsBindGroup(..), LRuleDecl, HsBind(..) )
16 import TcRnTypes        ( TcGblEnv(..), ImportAvails(..) )
17 import MkIface          ( mkUsageInfo )
18 import Id               ( Id, setIdLocalExported, idName, idIsFrom, isLocalId )
19 import Name             ( Name, isExternalName )
20 import CoreSyn
21 import PprCore          ( pprIdRules, pprCoreExpr )
22 import Subst            ( SubstResult(..), substExpr, mkSubst, extendIdSubstList )
23 import DsMonad
24 import DsExpr           ( dsLExpr )
25 import DsBinds          ( dsHsBinds, AutoScc(..) )
26 import DsForeign        ( dsForeigns )
27 import DsExpr           ()      -- Forces DsExpr to be compiled; DsBinds only
28                                 -- depends on DsExpr.hi-boot.
29 import Module           ( Module, ModuleName, moduleEnvElts, delModuleEnv, moduleNameFS )
30 import Id               ( Id )
31 import RdrName          ( GlobalRdrEnv )
32 import NameSet
33 import VarEnv
34 import VarSet
35 import Bag              ( Bag, isEmptyBag, mapBag, emptyBag, bagToList )
36 import CoreLint         ( showPass, endPass )
37 import CoreFVs          ( ruleRhsFreeVars )
38 import Packages         ( thPackage )
39 import ErrUtils         ( doIfSet, dumpIfSet_dyn, pprBagOfWarnings, 
40                           mkWarnMsg, errorsFound, WarnMsg )
41 import ListSetOps       ( insertList )
42 import Outputable
43 import UniqSupply       ( mkSplitUniqSupply )
44 import SrcLoc           ( Located(..), SrcSpan, unLoc )
45 import DATA_IOREF       ( readIORef )
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 (Bag WarnMsg, 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_type_env  = type_env,
63                             tcg_imports   = imports,
64                             tcg_exports   = exports,
65                             tcg_dus       = dus, 
66                             tcg_inst_uses = dfun_uses_var,
67                             tcg_th_used   = th_var,
68                             tcg_keep      = keep_var,
69                             tcg_rdr_env   = rdr_env,
70                             tcg_fix_env   = fix_env,
71                             tcg_deprecs   = deprecs,
72                             tcg_binds     = binds,
73                             tcg_fords     = fords,
74                             tcg_rules     = rules,
75                             tcg_insts     = insts })
76   = do  { showPass dflags "Desugar"
77
78         -- Desugar the program
79         ; ((all_prs, ds_rules, ds_fords), warns) 
80                 <- initDs hsc_env mod rdr_env type_env $ do
81                 { core_prs <- dsHsBinds auto_scc binds []
82                 ; (ds_fords, foreign_prs) <- dsForeigns fords
83                 ; let all_prs = foreign_prs ++ core_prs
84                       local_bndrs = mkVarSet (map fst all_prs)
85                 ; ds_rules <- mappM (dsRule mod local_bndrs) rules
86                 ; return (all_prs, ds_rules, ds_fords) }
87
88
89
90         -- If warnings are considered errors, leave.
91         ; if errorsFound dflags (warns, emptyBag)
92            then return (warns, Nothing)
93            else do
94
95         {       -- Add export flags to bindings
96           keep_alive <- readIORef keep_var
97         ; let final_prs = addExportFlags ghci_mode exports keep_alive 
98                                          all_prs ds_rules
99               ds_binds  = [Rec final_prs]
100         -- Notice that we put the whole lot in a big Rec, even the foreign binds
101         -- When compiling PrelFloat, which defines data Float = F# Float#
102         -- we want F# to be in scope in the foreign marshalling code!
103         -- You might think it doesn't matter, but the simplifier brings all top-level
104         -- things into the in-scope set before simplifying; so we get no unfolding for F#!
105
106         -- Lint result if necessary
107         ; endPass dflags "Desugar" Opt_D_dump_ds ds_binds
108
109         -- Dump output
110         ; doIfSet (dopt Opt_D_dump_ds dflags) 
111                   (printDump (ppr_ds_rules ds_rules))
112
113         ; dfun_uses <- readIORef dfun_uses_var          -- What dfuns are used
114         ; th_used   <- readIORef th_var                 -- Whether TH is used
115         ; let used_names = allUses dus `unionNameSets` dfun_uses
116               pkgs | th_used   = insertList thPackage (imp_dep_pkgs imports)
117                    | otherwise = imp_dep_pkgs imports
118
119               dep_mods = moduleEnvElts (delModuleEnv (imp_dep_mods imports) mod)
120                 -- M.hi-boot can be in the imp_dep_mods, but we must remove
121                 -- it before recording the modules on which this one depends!
122                 -- (We want to retain M.hi-boot in imp_dep_mods so that 
123                 --  loadHiBootInterface can see if M's direct imports depend 
124                 --  on M.hi-boot, and hence that we should do the hi-boot consistency 
125                 --  check.)
126
127               dir_imp_mods = imp_mods imports
128
129         ; usages <- mkUsageInfo hsc_env dir_imp_mods dep_mods used_names
130
131         ; let 
132                 -- ModuleNames don't compare lexicographically usually, 
133                 -- but we want them to do so here.
134              le_mod :: ModuleName -> ModuleName -> Bool  
135              le_mod m1 m2 = moduleNameFS m1 <= moduleNameFS m2
136              le_dep_mod :: (ModuleName, IsBootInterface) -> (ModuleName, IsBootInterface) -> Bool        
137              le_dep_mod (m1,_) (m2,_) = m1 `le_mod` m2
138
139              deps = Deps { dep_mods  = sortLe le_dep_mod dep_mods,
140                            dep_pkgs  = sortLe (<=)   pkgs,      
141                            dep_orphs = sortLe le_mod (imp_orphs imports) }
142                 -- sort to get into canonical order
143
144              mod_guts = ModGuts {       
145                 mg_module   = mod,
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_rules    = ds_rules,
156                 mg_binds    = ds_binds,
157                 mg_foreign  = ds_fords }
158         
159         ; return (warns, Just mod_guts)
160         }}
161
162   where
163     dflags       = hsc_dflags hsc_env
164     ghci_mode    = hsc_mode hsc_env
165     auto_scc | opt_SccProfilingOn = TopLevel
166              | otherwise          = NoSccs
167
168 deSugarExpr :: HscEnv
169             -> Module -> GlobalRdrEnv -> TypeEnv 
170             -> LHsExpr Id
171             -> IO CoreExpr
172 deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
173   = do  { showPass dflags "Desugar"
174         ; us <- mkSplitUniqSupply 'd'
175
176         -- Do desugaring
177         ; (core_expr, ds_warns) <- initDs hsc_env this_mod rdr_env type_env $
178                                    dsLExpr tc_expr
179
180         -- Display any warnings 
181         -- Note: if -Werror is used, we don't signal an error here.
182         ; doIfSet (not (isEmptyBag ds_warns))
183                   (printErrs (pprBagOfWarnings ds_warns))
184
185         -- Dump output
186         ; dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr core_expr)
187
188         ; return core_expr
189         }
190   where
191     dflags       = hsc_dflags hsc_env
192
193
194 --              addExportFlags
195 -- Set the no-discard flag if either 
196 --      a) the Id is exported
197 --      b) it's mentioned in the RHS of an orphan rule
198 --      c) it's in the keep-alive set
199 --
200 -- It means that the binding won't be discarded EVEN if the binding
201 -- ends up being trivial (v = w) -- the simplifier would usually just 
202 -- substitute w for v throughout, but we don't apply the substitution to
203 -- the rules (maybe we should?), so this substitution would make the rule
204 -- bogus.
205
206 -- You might wonder why exported Ids aren't already marked as such;
207 -- it's just because the type checker is rather busy already and
208 -- I didn't want to pass in yet another mapping.
209
210 addExportFlags ghci_mode exports keep_alive prs rules
211   = [(add_export bndr, rhs) | (bndr,rhs) <- prs]
212   where
213     add_export bndr
214         | isLocalId bndr && dont_discard bndr  = setIdLocalExported bndr
215                 -- The isLocalId check is to avoid fiddling with
216                 -- locally-defined Ids like data cons and class ops
217                 -- which are "born" as GlobalIds
218         | otherwise                            = bndr
219
220     orph_rhs_fvs = unionVarSets [ ruleRhsFreeVars rule
221                                 | IdCoreRule _ is_orphan_rule rule <- rules, 
222                                   is_orphan_rule ]
223         -- An orphan rule keeps alive the free vars of its right-hand side.  
224         -- Non-orphan rules are (later, after gentle simplification) 
225         -- attached to the Id and that keeps the rhs free vars alive
226
227     dont_discard bndr = is_exported name
228                      || name `elemNameSet` keep_alive
229                      || bndr `elemVarSet` orph_rhs_fvs 
230                      where
231                         name = idName bndr
232
233         -- In interactive mode, we don't want to discard any top-level
234         -- entities at all (eg. do not inline them away during
235         -- simplification), and retain them all in the TypeEnv so they are
236         -- available from the command line.
237         --
238         -- isExternalName separates the user-defined top-level names from those
239         -- introduced by the type checker.
240     is_exported :: Name -> Bool
241     is_exported | ghci_mode == Interactive = isExternalName
242                 | otherwise                = (`elemNameSet` exports)
243
244 ppr_ds_rules [] = empty
245 ppr_ds_rules rules
246   = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
247     pprIdRules rules
248 \end{code}
249
250
251
252 %************************************************************************
253 %*                                                                      *
254 %*              Desugaring transformation rules
255 %*                                                                      *
256 %************************************************************************
257
258 \begin{code}
259 dsRule :: Module -> IdSet -> LRuleDecl Id -> DsM IdCoreRule
260 dsRule mod in_scope (L loc (HsRule name act vars lhs rhs))
261   = putSrcSpanDs loc $ 
262     ds_lhs all_vars lhs         `thenDs` \ (fn, args) ->
263     dsLExpr rhs                 `thenDs` \ core_rhs ->
264     returnDs (IdCoreRule fn (is_orphan fn) (Rule name act tpl_vars args core_rhs))
265   where
266     tpl_vars  = [var | RuleBndr (L _ var) <- vars]
267     all_vars  = mkInScopeSet (extendVarSetList in_scope tpl_vars)
268     is_orphan id = not (idIsFrom mod id)
269         -- NB we can't use isLocalId in the orphan test, 
270         -- because isLocalId isn't true of class methods
271
272 ds_lhs all_vars lhs
273   = let
274         (dict_binds, body) = 
275            case unLoc lhs of
276                 (HsLet [HsBindGroup dict_binds _ _] body) -> (dict_binds, body)
277                 other                                  -> (emptyBag, lhs)
278     in
279     mappM ds_dict_bind (bagToList dict_binds)   `thenDs` \ dict_binds' ->
280     dsLExpr body                                `thenDs` \ body' ->
281
282         -- Substitute the dict bindings eagerly,
283         -- and take the body apart into a (f args) form
284     let
285         subst = extendIdSubstList (mkSubst all_vars) pairs
286         pairs = [(id, ContEx subst rhs) | (id,rhs) <- dict_binds']
287                         -- Note recursion here... substitution won't terminate
288                         -- if there is genuine recursion... which there isn't
289         body'' = substExpr subst body'
290     in
291         
292         -- Now unpack the resulting body
293     let
294         pair = case collectArgs body'' of
295                         (Var fn, args) -> (fn, args)
296                         other          -> pprPanic "dsRule" (ppr lhs)
297     in
298     returnDs pair
299
300 ds_dict_bind (L _ (VarBind id rhs)) =
301   dsLExpr rhs `thenDs` \ rhs' ->
302   returnDs (id,rhs')
303 \end{code}