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