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