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