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