[project @ 2002-04-11 12:03:29 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,
8                  deSugarCore ) where
9
10 #include "HsVersions.h"
11
12 import CmdLineOpts      ( DynFlags, DynFlag(..), dopt, opt_SccProfilingOn )
13 import HscTypes         ( ModDetails(..), TypeEnv )
14 import HsSyn            ( MonoBinds, RuleDecl(..), RuleBndr(..), 
15                           HsExpr(..), HsBinds(..), MonoBinds(..) )
16 import TcHsSyn          ( TypecheckedRuleDecl, TypecheckedHsExpr,
17                           TypecheckedCoreBind )
18 import TcModule         ( TcResults(..) )
19 import Id               ( Id )
20 import CoreSyn
21 import PprCore          ( pprIdRules, pprCoreExpr )
22 import Subst            ( substExpr, mkSubst, mkInScopeSet )
23 import DsMonad
24 import DsExpr           ( dsExpr )
25 import DsBinds          ( dsMonoBinds, AutoScc(..) )
26 import DsForeign        ( dsForeigns )
27 import DsExpr           ()      -- Forces DsExpr to be compiled; DsBinds only
28                                 -- depends on DsExpr.hi-boot.
29 import Module           ( Module )
30 import Id               ( Id )
31 import NameEnv          ( lookupNameEnv )
32 import VarEnv
33 import VarSet
34 import Bag              ( isEmptyBag )
35 import CoreLint         ( showPass, endPass )
36 import ErrUtils         ( doIfSet, dumpIfSet_dyn, pprBagOfWarnings )
37 import Outputable
38 import UniqSupply       ( mkSplitUniqSupply )
39 import HscTypes         ( HomeSymbolTable, PersistentCompilerState(..), TyThing(..), lookupType,  )
40 \end{code}
41
42 %************************************************************************
43 %*                                                                      *
44 %*              The main function: deSugar
45 %*                                                                      *
46 %************************************************************************
47
48 The only trick here is to get the @DsMonad@ stuff off to a good
49 start.
50
51 \begin{code}
52 deSugar :: DynFlags
53         -> PersistentCompilerState -> HomeSymbolTable
54         -> Module -> PrintUnqualified
55         -> TcResults
56         -> IO (ModDetails, (SDoc, SDoc, [FAST_STRING], [CoreBndr]))
57
58 deSugar dflags pcs hst mod_name unqual
59         (TcResults {tc_env    = type_env,
60                     tc_binds  = all_binds,
61                     tc_insts  = insts,
62                     tc_rules  = rules,
63                     tc_fords  = fo_decls})
64   = do  { showPass dflags "Desugar"
65         ; us <- mkSplitUniqSupply 'd'
66
67         -- Do desugaring
68         ; let (ds_result, ds_warns) = initDs dflags us lookup mod_name
69                                              (dsProgram mod_name all_binds rules fo_decls)    
70
71               (ds_binds, ds_rules, foreign_stuff) = ds_result
72               
73               mod_details = ModDetails { md_types = type_env,
74                                          md_insts = insts,
75                                          md_rules = ds_rules,
76                                          md_binds = ds_binds }
77
78         -- Display any warnings
79         ; doIfSet (not (isEmptyBag ds_warns))
80                   (printErrs unqual (pprBagOfWarnings ds_warns))
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         ; return (mod_details, foreign_stuff)
90         }
91
92   where
93         -- The lookup function passed to initDs is used for well-known Ids, 
94         -- such as fold, build, cons etc, so the chances are
95         -- it'll be found in the package symbol table.  That's
96         -- why we don't merge all these tables
97     pte      = pcs_PTE pcs
98     lookup n = case lookupType hst pte n of {
99                  Just (AnId v) -> v ;
100                  other -> 
101                case lookupNameEnv type_env n of
102                  Just (AnId v) -> v ;
103                  other         -> pprPanic "Desugar: lookup:" (ppr n)
104                }
105
106 deSugarExpr :: DynFlags
107             -> PersistentCompilerState -> HomeSymbolTable
108             -> Module -> PrintUnqualified
109             -> TypecheckedHsExpr
110             -> IO CoreExpr
111 deSugarExpr dflags pcs hst mod_name unqual tc_expr
112   = do  { showPass dflags "Desugar"
113         ; us <- mkSplitUniqSupply 'd'
114
115         -- Do desugaring
116         ; let (core_expr, ds_warns) = initDs dflags us lookup mod_name (dsExpr tc_expr)    
117
118         -- Display any warnings
119         ; doIfSet (not (isEmptyBag ds_warns))
120                   (printErrs unqual (pprBagOfWarnings ds_warns))
121
122         -- Dump output
123         ; dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr core_expr)
124
125         ; return core_expr
126         }
127   where
128     pte      = pcs_PTE pcs
129     lookup n = case lookupType hst pte n of
130                  Just (AnId v) -> v 
131                  other         -> pprPanic "Desugar: lookup:" (ppr n)
132
133 dsProgram mod_name all_binds rules fo_decls
134   = dsMonoBinds auto_scc all_binds []   `thenDs` \ core_prs ->
135     dsForeigns mod_name fo_decls        `thenDs` \ (fe_binders, foreign_binds, h_code, c_code, headers) ->
136     let
137         ds_binds      = [Rec (foreign_binds ++ core_prs)]
138         -- Notice that we put the whole lot in a big Rec, even the foreign binds
139         -- When compiling PrelFloat, which defines data Float = F# Float#
140         -- we want F# to be in scope in the foreign marshalling code!
141         -- You might think it doesn't matter, but the simplifier brings all top-level
142         -- things into the in-scope set before simplifying; so we get no unfolding for F#!
143
144         local_binders = mkVarSet (bindersOfBinds ds_binds)
145     in
146     mapDs (dsRule local_binders) rules  `thenDs` \ rules' ->
147     returnDs (ds_binds, rules', (h_code, c_code, headers, fe_binders))
148   where
149     auto_scc | opt_SccProfilingOn = TopLevel
150              | otherwise          = NoSccs
151
152 ppr_ds_rules [] = empty
153 ppr_ds_rules rules
154   = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
155     pprIdRules rules
156 \end{code}
157
158 Simplest thing in the world, desugaring External Core:
159
160 \begin{code}
161 deSugarCore :: (TypeEnv, [TypecheckedCoreBind], [TypecheckedRuleDecl])
162             -> IO (ModDetails, (SDoc, SDoc, [FAST_STRING], [CoreBndr]))
163 deSugarCore (type_env, pairs, rules) 
164   = return (mod_details, no_foreign_stuff)
165   where
166     mod_details = ModDetails { md_types = type_env
167                              , md_insts = []
168                              , md_rules = ds_rules
169                              , md_binds = ds_binds }
170     ds_binds = [Rec pairs]
171     ds_rules = [(fun,rule) | IfaceRuleOut fun rule <- rules]
172
173     no_foreign_stuff = (empty,empty,[],[])
174 \end{code}
175
176
177 %************************************************************************
178 %*                                                                      *
179 %*              Desugaring transformation rules
180 %*                                                                      *
181 %************************************************************************
182
183 \begin{code}
184 dsRule :: IdSet -> TypecheckedRuleDecl -> DsM (Id, CoreRule)
185 dsRule in_scope (IfaceRuleOut fun rule) -- Built-in rules come this way
186   = returnDs (fun, rule)
187
188 dsRule in_scope (HsRule name act vars lhs rhs loc)
189   = putSrcLocDs loc             $
190     ds_lhs all_vars lhs         `thenDs` \ (fn, args) ->
191     dsExpr rhs                  `thenDs` \ core_rhs ->
192     returnDs (fn, Rule name act tpl_vars args core_rhs)
193   where
194     tpl_vars = [var | RuleBndr var <- vars]
195     all_vars = mkInScopeSet (in_scope `unionVarSet` mkVarSet tpl_vars)
196
197 ds_lhs all_vars lhs
198   = let
199         (dict_binds, body) = case lhs of
200                 (HsLet (MonoBind dict_binds _ _) body) -> (dict_binds, body)
201                 other                                  -> (EmptyMonoBinds, lhs)
202     in
203     ds_dict_binds dict_binds    `thenDs` \ dict_binds' ->
204     dsExpr body                 `thenDs` \ body' ->
205
206         -- Substitute the dict bindings eagerly,
207         -- and take the body apart into a (f args) form
208     let
209         subst_env = mkSubstEnv [id                   | (id,rhs) <- dict_binds']
210                                [ContEx subst_env rhs | (id,rhs) <- dict_binds']
211                         -- Note recursion here... substitution won't terminate
212                         -- if there is genuine recursion... which there isn't
213
214         subst = mkSubst all_vars subst_env
215         body'' = substExpr subst body'
216     in
217         
218         -- Now unpack the resulting body
219     let
220         pair = case collectArgs body'' of
221                         (Var fn, args) -> (fn, args)
222                         other          -> pprPanic "dsRule" (ppr lhs)
223     in
224     returnDs pair
225
226 ds_dict_binds EmptyMonoBinds       = returnDs []
227 ds_dict_binds (AndMonoBinds b1 b2) = ds_dict_binds b1   `thenDs` \ env1 ->
228                                      ds_dict_binds b2   `thenDs` \ env2 ->
229                                      returnDs (env1 ++ env2)
230 ds_dict_binds (VarMonoBind id rhs) = dsExpr rhs         `thenDs` \ rhs' ->
231                                      returnDs [(id,rhs')]
232 \end{code}