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