[project @ 2002-09-13 15:02:25 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(..), ExternalPackageState(..), 
13                           PersistentCompilerState(..), 
14                           lookupType )
15 import HsSyn            ( MonoBinds, RuleDecl(..), RuleBndr(..), 
16                           HsExpr(..), HsBinds(..), MonoBinds(..) )
17 import TcHsSyn          ( TypecheckedRuleDecl, TypecheckedHsExpr )
18 import TcRnTypes        ( TcGblEnv(..), ImportAvails(imp_mods) )
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 )
31 import Id               ( Id )
32 import NameEnv          ( lookupNameEnv )
33 import VarEnv
34 import VarSet
35 import Bag              ( isEmptyBag )
36 import CoreLint         ( showPass, endPass )
37 import ErrUtils         ( doIfSet, dumpIfSet_dyn, pprBagOfWarnings, addShortWarnLocLine )
38 import Outputable
39 import UniqSupply       ( mkSplitUniqSupply )
40 import FastString
41 import DATA_IOREF       ( readIORef )
42 \end{code}
43
44 %************************************************************************
45 %*                                                                      *
46 %*              The main function: deSugar
47 %*                                                                      *
48 %************************************************************************
49
50 \begin{code}
51 deSugar :: HscEnv -> PersistentCompilerState
52         -> TcGblEnv -> IO ModGuts
53
54 deSugar hsc_env pcs
55         (TcGblEnv { tcg_mod      = mod,
56                     tcg_type_env = type_env,
57                     tcg_usages   = usage_var,
58                     tcg_imports  = imports,
59                     tcg_exports  = exports,
60                     tcg_rdr_env  = rdr_env,
61                     tcg_fix_env  = fix_env,
62                     tcg_deprecs  = deprecs,
63                     tcg_insts    = insts,
64                     tcg_binds    = binds,
65                     tcg_fords    = fords,
66                     tcg_rules    = rules })
67   = do  { showPass dflags "Desugar"
68         ; us <- mkSplitUniqSupply 'd'
69         ; usages <- readIORef usage_var 
70
71         -- Do desugaring
72         ; let ((ds_binds, ds_rules, ds_fords), ds_warns) 
73                 = initDs dflags us lookup mod
74                          (dsProgram binds rules fords)
75         
76               warn_doc = pprBagOfWarnings (mapBag mk_warn ds_warns))
77
78         -- Display any warnings
79         ; doIfSet (not (isEmptyBag ds_warns))
80                   (printErrs warn_doc)
81
82         -- Lint result if necessary
83         ; endPass dflags "Desugar" Opt_D_dump_ds ds_binds
84
85         -- Dump output
86         ; doIfSet (dopt Opt_D_dump_ds dflags) 
87                   (printDump (ppr_ds_rules ds_rules))
88
89         ; let 
90              mod_guts = ModGuts {       
91                 mg_module   = mod,
92                 mg_exports  = exports,
93                 mg_usages   = mkUsageInfo hsc_env eps imports usages,
94                 mg_dir_imps = [m | (m,_) <- moduleEnvElts (imp_mods imports)],
95                 mg_rdr_env  = rdr_env,
96                 mg_fix_env  = fix_env,
97                 mg_deprecs  = deprecs,
98                 mg_types    = type_env,
99                 mg_insts    = insts,
100                 mg_rules    = ds_rules,
101                 mg_binds    = ds_binds,
102                 mg_foreign  = ds_fords }
103         
104         ; return mod_guts
105         }
106
107   where
108     dflags       = hsc_dflags hsc_env
109     print_unqual = unQualInScope rdr_env
110
111         -- Desugarer warnings are SDocs; here we
112         -- add the info about whether or not to print unqualified
113     mk_warn (loc,sdoc) = (loc, addShortWarnLocLine loc print_unqual sdoc)
114
115         -- The lookup function passed to initDs is used for well-known Ids, 
116         -- such as fold, build, cons etc, so the chances are
117         -- it'll be found in the package symbol table.  That's
118         -- why we don't merge all these tables
119     eps      = pcs_EPS pcs
120     pte      = eps_PTE eps
121     hpt      = hsc_HPT hsc_env
122     lookup n = case lookupType hpt pte n of {
123                  Just v -> v ;
124                  other -> 
125                case lookupNameEnv type_env n of
126                  Just v -> v ;
127                  other         -> pprPanic "Desugar: lookup:" (ppr n)
128                }
129
130 deSugarExpr :: HscEnv
131             -> PersistentCompilerState
132             -> Module -> PrintUnqualified
133             -> TypecheckedHsExpr
134             -> IO CoreExpr
135 deSugarExpr hsc_env pcs mod_name unqual tc_expr
136   = do  { showPass dflags "Desugar"
137         ; us <- mkSplitUniqSupply 'd'
138
139         -- Do desugaring
140         ; let (core_expr, ds_warns) = initDs dflags us lookup mod_name (dsExpr tc_expr)    
141
142         -- Display any warnings
143         ; doIfSet (not (isEmptyBag ds_warns))
144                   (printErrs (pprBagOfWarnings ds_warns))
145
146         -- Dump output
147         ; dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr core_expr)
148
149         ; return core_expr
150         }
151   where
152     dflags   = hsc_dflags hsc_env
153     hpt      = hsc_HPT hsc_env
154     pte      = eps_PTE (pcs_EPS pcs)
155     lookup n = case lookupType hpt pte n of
156                  Just v -> v 
157                  other  -> pprPanic "Desugar: lookup:" (ppr n)
158
159 dsProgram all_binds rules fo_decls
160   = dsMonoBinds auto_scc all_binds []   `thenDs` \ core_prs ->
161     dsForeigns fo_decls                 `thenDs` \ (ds_fords, foreign_binds) ->
162     let
163         ds_binds      = [Rec (foreign_binds ++ core_prs)]
164         -- Notice that we put the whole lot in a big Rec, even the foreign binds
165         -- When compiling PrelFloat, which defines data Float = F# Float#
166         -- we want F# to be in scope in the foreign marshalling code!
167         -- You might think it doesn't matter, but the simplifier brings all top-level
168         -- things into the in-scope set before simplifying; so we get no unfolding for F#!
169
170         local_binders = mkVarSet (bindersOfBinds ds_binds)
171     in
172     mapDs (dsRule local_binders) rules  `thenDs` \ ds_rules ->
173     returnDs (ds_binds, ds_rules, ds_fords)
174   where
175     auto_scc | opt_SccProfilingOn = TopLevel
176              | otherwise          = NoSccs
177
178 ppr_ds_rules [] = empty
179 ppr_ds_rules rules
180   = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
181     pprIdRules rules
182 \end{code}
183
184
185
186 %************************************************************************
187 %*                                                                      *
188 %*              Desugaring transformation rules
189 %*                                                                      *
190 %************************************************************************
191
192 \begin{code}
193 dsRule :: IdSet -> TypecheckedRuleDecl -> DsM (Id, CoreRule)
194 dsRule in_scope (IfaceRuleOut fun rule) -- Built-in rules come this way
195   = returnDs (fun, rule)
196
197 dsRule in_scope (HsRule name act vars lhs rhs loc)
198   = putSrcLocDs loc             $
199     ds_lhs all_vars lhs         `thenDs` \ (fn, args) ->
200     dsExpr rhs                  `thenDs` \ core_rhs ->
201     returnDs (fn, Rule name act tpl_vars args core_rhs)
202   where
203     tpl_vars = [var | RuleBndr var <- vars]
204     all_vars = mkInScopeSet (in_scope `unionVarSet` mkVarSet tpl_vars)
205
206 ds_lhs all_vars lhs
207   = let
208         (dict_binds, body) = case lhs of
209                 (HsLet (MonoBind dict_binds _ _) body) -> (dict_binds, body)
210                 other                                  -> (EmptyMonoBinds, lhs)
211     in
212     ds_dict_binds dict_binds    `thenDs` \ dict_binds' ->
213     dsExpr body                 `thenDs` \ body' ->
214
215         -- Substitute the dict bindings eagerly,
216         -- and take the body apart into a (f args) form
217     let
218         subst_env = mkSubstEnv [id                   | (id,rhs) <- dict_binds']
219                                [ContEx subst_env rhs | (id,rhs) <- dict_binds']
220                         -- Note recursion here... substitution won't terminate
221                         -- if there is genuine recursion... which there isn't
222
223         subst = mkSubst all_vars subst_env
224         body'' = substExpr subst body'
225     in
226         
227         -- Now unpack the resulting body
228     let
229         pair = case collectArgs body'' of
230                         (Var fn, args) -> (fn, args)
231                         other          -> pprPanic "dsRule" (ppr lhs)
232     in
233     returnDs pair
234
235 ds_dict_binds EmptyMonoBinds       = returnDs []
236 ds_dict_binds (AndMonoBinds b1 b2) = ds_dict_binds b1   `thenDs` \ env1 ->
237                                      ds_dict_binds b2   `thenDs` \ env2 ->
238                                      returnDs (env1 ++ env2)
239 ds_dict_binds (VarMonoBind id rhs) = dsExpr rhs         `thenDs` \ rhs' ->
240                                      returnDs [(id,rhs')]
241 \end{code}