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