[project @ 2003-10-09 11:58:39 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(..), dopt, opt_SccProfilingOn )
12 import HscTypes         ( ModGuts(..), ModGuts, HscEnv(..), 
13                           Dependencies(..), TypeEnv, 
14                           unQualInScope )
15 import HsSyn            ( MonoBinds, RuleDecl(..), RuleBndr(..), 
16                           HsExpr(..), HsBinds(..), MonoBinds(..) )
17 import TcHsSyn          ( TypecheckedRuleDecl, TypecheckedHsExpr )
18 import TcRnTypes        ( TcGblEnv(..), ImportAvails(..) )
19 import MkIface          ( mkUsageInfo )
20 import Id               ( Id )
21 import CoreSyn
22 import PprCore          ( pprIdRules, pprCoreExpr )
23 import Subst            ( substExpr, mkSubst, mkInScopeSet )
24 import DsMonad
25 import DsExpr           ( dsExpr )
26 import DsBinds          ( dsMonoBinds, 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, emptyModuleEnv )
31 import Id               ( Id )
32 import RdrName          ( GlobalRdrEnv )
33 import NameSet
34 import VarEnv
35 import VarSet
36 import Bag              ( isEmptyBag, mapBag, emptyBag )
37 import CoreLint         ( showPass, endPass )
38 import ErrUtils         ( doIfSet, dumpIfSet_dyn, pprBagOfWarnings, 
39                           addShortWarnLocLine, errorsFound )
40 import Outputable
41 import qualified Pretty
42 import UniqSupply       ( mkSplitUniqSupply )
43 import SrcLoc           ( SrcLoc )
44 import DATA_IOREF       ( readIORef )
45 import FastString
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         (TcGblEnv { tcg_mod       = mod,
60                     tcg_type_env  = type_env,
61                     tcg_imports   = imports,
62                     tcg_exports   = exports,
63                     tcg_dus       = dus, 
64                     tcg_inst_uses = dfun_uses_var,
65                     tcg_rdr_env   = rdr_env,
66                     tcg_fix_env   = fix_env,
67                     tcg_deprecs   = deprecs,
68                     tcg_insts     = insts,
69                     tcg_binds     = binds,
70                     tcg_fords     = fords,
71                     tcg_rules     = rules })
72   = do  { showPass dflags "Desugar"
73
74         -- Do desugaring
75         ; let { is_boot = imp_dep_mods imports }
76         ; (results, warnings) <- initDs hsc_env mod type_env is_boot $
77                                  dsProgram binds rules fords
78
79         ; let { (ds_binds, ds_rules, ds_fords) = results
80               ; warns    = mapBag mk_warn warnings
81               ; warn_doc = pprBagOfWarnings warns }
82
83         -- Display any warnings
84         ; doIfSet (not (isEmptyBag warnings))
85                   (printErrs warn_doc)
86
87             -- if warnings are considered errors, leave.
88         ; if errorsFound dflags (warns, emptyBag)
89            then return Nothing
90            else do {
91
92         -- Lint result if necessary
93           endPass dflags "Desugar" Opt_D_dump_ds ds_binds
94
95         -- Dump output
96         ; doIfSet (dopt Opt_D_dump_ds dflags) 
97                   (printDump (ppr_ds_rules ds_rules))
98
99         ; dfun_uses <- readIORef dfun_uses_var          -- What dfuns are used
100         ; let used_names = allUses dus emptyNameSet `unionNameSets` dfun_uses
101         ; usages <- mkUsageInfo hsc_env imports used_names
102         ; let 
103              deps = Deps { dep_mods = moduleEnvElts (imp_dep_mods imports), 
104                            dep_pkgs = imp_dep_pkgs imports,
105                            dep_orphs = imp_orphs imports }
106              mod_guts = ModGuts {       
107                 mg_module   = mod,
108                 mg_exports  = exports,
109                 mg_deps     = deps,
110                 mg_usages   = usages,
111                 mg_dir_imps = [m | (m,_) <- moduleEnvElts (imp_mods imports)],
112                 mg_rdr_env  = rdr_env,
113                 mg_fix_env  = fix_env,
114                 mg_deprecs  = deprecs,
115                 mg_types    = type_env,
116                 mg_insts    = insts,
117                 mg_rules    = ds_rules,
118                 mg_binds    = ds_binds,
119                 mg_foreign  = ds_fords }
120         
121         ; return (Just mod_guts)
122         }}
123
124   where
125     dflags       = hsc_dflags hsc_env
126     print_unqual = unQualInScope rdr_env
127
128         -- Desugarer warnings are SDocs; here we
129         -- add the info about whether or not to print unqualified
130     mk_warn :: (SrcLoc,SDoc) -> (SrcLoc, Pretty.Doc)
131     mk_warn (loc, sdoc) = addShortWarnLocLine loc print_unqual sdoc
132
133
134 deSugarExpr :: HscEnv
135             -> Module -> GlobalRdrEnv -> TypeEnv 
136             -> TypecheckedHsExpr
137             -> IO CoreExpr
138 deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
139   = do  { showPass dflags "Desugar"
140         ; us <- mkSplitUniqSupply 'd'
141
142         -- Do desugaring
143         ; let { is_boot = emptyModuleEnv }      -- Assume no hi-boot files when
144                                                 -- doing stuff from the command line
145         ; (core_expr, ds_warns) <- initDs hsc_env this_mod type_env is_boot $
146                                    dsExpr tc_expr
147
148         -- Display any warnings 
149         -- Note: if -Werror is used, we don't signal an error here.
150         ; doIfSet (not (isEmptyBag ds_warns))
151                   (printErrs (pprBagOfWarnings (mapBag mk_warn ds_warns)))
152
153         -- Dump output
154         ; dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr core_expr)
155
156         ; return core_expr
157         }
158   where
159     dflags       = hsc_dflags hsc_env
160     print_unqual = unQualInScope rdr_env
161
162     mk_warn :: (SrcLoc,SDoc) -> (SrcLoc, Pretty.Doc)
163     mk_warn (loc,sdoc) = addShortWarnLocLine loc print_unqual sdoc
164
165
166 dsProgram all_binds rules fo_decls
167   = dsMonoBinds auto_scc all_binds []   `thenDs` \ core_prs ->
168     dsForeigns fo_decls                 `thenDs` \ (ds_fords, foreign_binds) ->
169     let
170         ds_binds      = [Rec (foreign_binds ++ core_prs)]
171         -- Notice that we put the whole lot in a big Rec, even the foreign binds
172         -- When compiling PrelFloat, which defines data Float = F# Float#
173         -- we want F# to be in scope in the foreign marshalling code!
174         -- You might think it doesn't matter, but the simplifier brings all top-level
175         -- things into the in-scope set before simplifying; so we get no unfolding for F#!
176
177         local_binders = mkVarSet (bindersOfBinds ds_binds)
178     in
179     mappM (dsRule local_binders) rules  `thenDs` \ ds_rules ->
180     returnDs (ds_binds, ds_rules, ds_fords)
181   where
182     auto_scc | opt_SccProfilingOn = TopLevel
183              | otherwise          = NoSccs
184
185 ppr_ds_rules [] = empty
186 ppr_ds_rules rules
187   = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
188     pprIdRules rules
189 \end{code}
190
191
192
193 %************************************************************************
194 %*                                                                      *
195 %*              Desugaring transformation rules
196 %*                                                                      *
197 %************************************************************************
198
199 \begin{code}
200 dsRule :: IdSet -> TypecheckedRuleDecl -> DsM (Id, CoreRule)
201 dsRule in_scope (HsRule name act vars lhs rhs loc)
202   = putSrcLocDs loc             $
203     ds_lhs all_vars lhs         `thenDs` \ (fn, args) ->
204     dsExpr rhs                  `thenDs` \ core_rhs ->
205     returnDs (fn, Rule name act tpl_vars args core_rhs)
206   where
207     tpl_vars = [var | RuleBndr var <- vars]
208     all_vars = mkInScopeSet (in_scope `unionVarSet` mkVarSet tpl_vars)
209
210 ds_lhs all_vars lhs
211   = let
212         (dict_binds, body) = case lhs of
213                 (HsLet (MonoBind dict_binds _ _) body) -> (dict_binds, body)
214                 other                                  -> (EmptyMonoBinds, lhs)
215     in
216     ds_dict_binds dict_binds    `thenDs` \ dict_binds' ->
217     dsExpr body                 `thenDs` \ body' ->
218
219         -- Substitute the dict bindings eagerly,
220         -- and take the body apart into a (f args) form
221     let
222         subst_env = mkSubstEnv [id                   | (id,rhs) <- dict_binds']
223                                [ContEx subst_env rhs | (id,rhs) <- dict_binds']
224                         -- Note recursion here... substitution won't terminate
225                         -- if there is genuine recursion... which there isn't
226
227         subst = mkSubst all_vars subst_env
228         body'' = substExpr subst body'
229     in
230         
231         -- Now unpack the resulting body
232     let
233         pair = case collectArgs body'' of
234                         (Var fn, args) -> (fn, args)
235                         other          -> pprPanic "dsRule" (ppr lhs)
236     in
237     returnDs pair
238
239 ds_dict_binds EmptyMonoBinds       = returnDs []
240 ds_dict_binds (AndMonoBinds b1 b2) = ds_dict_binds b1   `thenDs` \ env1 ->
241                                      ds_dict_binds b2   `thenDs` \ env2 ->
242                                      returnDs (env1 ++ env2)
243 ds_dict_binds (VarMonoBind id rhs) = dsExpr rhs         `thenDs` \ rhs' ->
244                                      returnDs [(id,rhs')]
245 \end{code}