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