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