[project @ 2002-04-05 15:18:25 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,
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_cbinds = core_binds,
64                     tc_fords  = fo_decls})
65   = do  { showPass dflags "Desugar"
66         ; us <- mkSplitUniqSupply 'd'
67
68         -- Do desugaring
69         ; let (ds_result, ds_warns) = initDs dflags us lookup mod_name
70                                              (dsProgram mod_name all_binds rules fo_decls)    
71
72               (ds_binds, ds_rules, foreign_stuff) = ds_result
73               
74 {-
75               addCoreBinds ls =
76                 case core_binds of
77                   [] -> ls
78                   cs -> (Rec cs) : ls
79 -}      
80               mod_details = ModDetails { md_types = type_env,
81                                          md_insts = insts,
82                                          md_rules = ds_rules,
83                                          md_binds = ds_binds }
84
85         -- Display any warnings
86         ; doIfSet (not (isEmptyBag ds_warns))
87                   (printErrs unqual (pprBagOfWarnings ds_warns))
88
89         -- Lint result if necessary
90         ; endPass dflags "Desugar" Opt_D_dump_ds ds_binds
91
92         -- Dump output
93         ; doIfSet (dopt Opt_D_dump_ds dflags) 
94                 (printDump (ppr_ds_rules ds_rules))
95
96         ; return (mod_details, foreign_stuff)
97         }
98
99   where
100         -- The lookup function passed to initDs is used for well-known Ids, 
101         -- such as fold, build, cons etc, so the chances are
102         -- it'll be found in the package symbol table.  That's
103         -- why we don't merge all these tables
104     pte      = pcs_PTE pcs
105     lookup n = case lookupType hst pte n of {
106                  Just (AnId v) -> v ;
107                  other -> 
108                case lookupNameEnv type_env n of
109                  Just (AnId v) -> v ;
110                  other         -> pprPanic "Desugar: lookup:" (ppr n)
111                }
112
113 deSugarExpr :: DynFlags
114             -> PersistentCompilerState -> HomeSymbolTable
115             -> Module -> PrintUnqualified
116             -> TypecheckedHsExpr
117             -> IO CoreExpr
118 deSugarExpr dflags pcs hst mod_name unqual tc_expr
119   = do  { showPass dflags "Desugar"
120         ; us <- mkSplitUniqSupply 'd'
121
122         -- Do desugaring
123         ; let (core_expr, ds_warns) = initDs dflags us lookup mod_name (dsExpr tc_expr)    
124
125         -- Display any warnings
126         ; doIfSet (not (isEmptyBag ds_warns))
127                   (printErrs unqual (pprBagOfWarnings ds_warns))
128
129         -- Dump output
130         ; dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr core_expr)
131
132         ; return core_expr
133         }
134   where
135     pte      = pcs_PTE pcs
136     lookup n = case lookupType hst pte n of
137                  Just (AnId v) -> v 
138                  other         -> pprPanic "Desugar: lookup:" (ppr n)
139
140 dsProgram mod_name all_binds rules fo_decls
141   = dsMonoBinds auto_scc all_binds []   `thenDs` \ core_prs ->
142     dsForeigns mod_name fo_decls        `thenDs` \ (fe_binders, foreign_binds, h_code, c_code, headers) ->
143     let
144         ds_binds      = [Rec (foreign_binds ++ core_prs)]
145         -- Notice that we put the whole lot in a big Rec, even the foreign binds
146         -- When compiling PrelFloat, which defines data Float = F# Float#
147         -- we want F# to be in scope in the foreign marshalling code!
148         -- You might think it doesn't matter, but the simplifier brings all top-level
149         -- things into the in-scope set before simplifying; so we get no unfolding for F#!
150
151         local_binders = mkVarSet (bindersOfBinds ds_binds)
152     in
153     mapDs (dsRule local_binders) rules  `thenDs` \ rules' ->
154     returnDs (ds_binds, rules', (h_code, c_code, headers, fe_binders))
155   where
156     auto_scc | opt_SccProfilingOn = TopLevel
157              | otherwise          = NoSccs
158
159 ppr_ds_rules [] = empty
160 ppr_ds_rules rules
161   = text "" $$ text "-------------- DESUGARED RULES -----------------" $$
162     pprIdRules rules
163 \end{code}
164
165 Simplest thing in the world, desugaring External Core:
166
167 \begin{code}
168 deSugarCore :: TypeEnv -> [TypecheckedCoreBind]
169             -> IO (ModDetails, (SDoc, SDoc, [FAST_STRING], [CoreBndr]))
170 deSugarCore type_env cs = do
171   let
172     mod_details 
173       = ModDetails { md_types = type_env
174                    , md_insts = []
175                    , md_rules = []
176                    , md_binds = [Rec (map (\ (lhs,_,rhs) -> (lhs,rhs)) cs)]
177                    }
178
179     no_foreign_stuff = (empty,empty,[],[])
180   return (mod_details, no_foreign_stuff)
181     
182 \end{code}
183
184
185 %************************************************************************
186 %*                                                                      *
187 %*              Desugaring transformation rules
188 %*                                                                      *
189 %************************************************************************
190
191 \begin{code}
192 dsRule :: IdSet -> TypecheckedRuleDecl -> DsM (Id, CoreRule)
193 dsRule in_scope (IfaceRuleOut fun rule) -- Built-in rules come this way
194   = returnDs (fun, rule)
195
196 dsRule in_scope (HsRule name act vars lhs rhs loc)
197   = putSrcLocDs loc             $
198     ds_lhs all_vars lhs         `thenDs` \ (fn, args) ->
199     dsExpr rhs                  `thenDs` \ core_rhs ->
200     returnDs (fn, Rule name act tpl_vars args core_rhs)
201   where
202     tpl_vars = [var | RuleBndr var <- vars]
203     all_vars = mkInScopeSet (in_scope `unionVarSet` mkVarSet tpl_vars)
204
205 ds_lhs all_vars lhs
206   = let
207         (dict_binds, body) = case lhs of
208                 (HsLet (MonoBind dict_binds _ _) body) -> (dict_binds, body)
209                 other                                  -> (EmptyMonoBinds, lhs)
210     in
211     ds_dict_binds dict_binds    `thenDs` \ dict_binds' ->
212     dsExpr body                 `thenDs` \ body' ->
213
214         -- Substitute the dict bindings eagerly,
215         -- and take the body apart into a (f args) form
216     let
217         subst_env = mkSubstEnv [id                   | (id,rhs) <- dict_binds']
218                                [ContEx subst_env rhs | (id,rhs) <- dict_binds']
219                         -- Note recursion here... substitution won't terminate
220                         -- if there is genuine recursion... which there isn't
221
222         subst = mkSubst all_vars subst_env
223         body'' = substExpr subst body'
224     in
225         
226         -- Now unpack the resulting body
227     let
228         pair = case collectArgs body'' of
229                         (Var fn, args) -> (fn, args)
230                         other          -> pprPanic "dsRule" (ppr lhs)
231     in
232     returnDs pair
233
234 ds_dict_binds EmptyMonoBinds       = returnDs []
235 ds_dict_binds (AndMonoBinds b1 b2) = ds_dict_binds b1   `thenDs` \ env1 ->
236                                      ds_dict_binds b2   `thenDs` \ env2 ->
237                                      returnDs (env1 ++ env2)
238 ds_dict_binds (VarMonoBind id rhs) = dsExpr rhs         `thenDs` \ rhs' ->
239                                      returnDs [(id,rhs')]
240 \end{code}