[project @ 2000-10-23 16:39:11 by simonpj]
[ghc-hetmet.git] / ghc / compiler / main / HscMain.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
3 %
4 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
5
6 \begin{code}
7 module HscMain ( hscMain ) where
8
9 #include "HsVersions.h"
10
11 import IO               ( hPutStr, stderr )
12 import HsSyn
13
14 import RdrHsSyn         ( RdrNameHsModule )
15 import FastString       ( unpackFS )
16 import StringBuffer     ( hGetStringBuffer )
17 import Parser           ( parse )
18 import Lex              ( PState(..), ParseResult(..) )
19 import SrcLoc           ( mkSrcLoc )
20
21 import Rename           ( renameModule )
22
23 import PrelInfo         ( wiredInThings )
24 import PrelRules        ( builtinRules )
25 import MkIface          ( writeIface )
26 import TcModule         ( TcResults(..), typecheckModule )
27 import Desugar          ( deSugar )
28 import SimplCore        ( core2core )
29 import OccurAnal        ( occurAnalyseBinds )
30 import CoreUtils        ( coreBindsSize )
31 import CoreTidy         ( tidyCorePgm )
32 import CoreToStg        ( topCoreBindsToStg )
33 import StgSyn           ( collectFinalStgBinders )
34 import SimplStg         ( stg2stg )
35 import CodeGen          ( codeGen )
36 import CodeOutput       ( codeOutput )
37
38 import Module           ( ModuleName, moduleNameUserString )
39 import CmdLineOpts
40 import ErrUtils         ( ghcExit, doIfSet, dumpIfSet )
41 import UniqSupply       ( mkSplitUniqSupply )
42
43 import Outputable
44 import Char             ( isSpace )
45 import StgInterp        ( runStgI )
46 import HscStats         ( ppSourceStats )
47 \end{code}
48
49
50 %************************************************************************
51 %*                                                                      *
52 \subsection{The main compiler pipeline}
53 %*                                                                      *
54 %************************************************************************
55
56 \begin{code}
57 data HscResult
58    = HscOK   ModDetails              -- new details (HomeSymbolTable additions)
59              (Maybe ModIface)        -- new iface (if any compilation was done)
60              (Maybe String)          -- generated stub_h filename (in /tmp)
61              (Maybe String)          -- generated stub_c filename (in /tmp)
62              (Maybe [UnlinkedIBind]) -- interpreted code, if any
63              PersistentCompilerState -- updated PCS
64              (Bag WarnMsg)              -- warnings
65
66    | HscErrs PersistentCompilerState -- updated PCS
67              (Bag ErrMsg)               -- errors
68              (Bag WarnMsg)             -- warnings
69
70 hscMain
71   :: DynFlags   
72   -> ModSummary       -- summary, including source filename
73   -> Maybe ModIFace   -- old interface, if available
74   -> String           -- file in which to put the output (.s, .hc, .java etc.)
75   -> HomeSymbolTable            -- for home module ModDetails
76   -> PersistentCompilerState    -- IN: persistent compiler state
77   -> IO HscResult
78
79 hscMain flags core_cmds stg_cmds summary maybe_old_iface
80         output_filename mod_details pcs1 =
81
82         --------------------------  Reader  ----------------
83     show_pass "Parser"  >>
84     _scc_     "Parser"
85
86     let src_filename -- name of the preprocessed source file
87        = case ms_ppsource summary of
88             Just (filename, fingerprint) -> filename
89             Nothing -> pprPanic "hscMain:summary is not of a source module"
90                                 (ppr summary)
91
92     buf <- hGetStringBuffer True{-expand tabs-} src_filename
93
94     let glaexts | opt_GlasgowExts = 1#
95                 | otherwise       = 0#
96
97     case parse buf PState{ bol = 0#, atbol = 1#,
98                            context = [], glasgow_exts = glaexts,
99                            loc = mkSrcLoc src_filename 1 } of {
100
101         PFailed err -> return (CompErrs pcs err)
102
103         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) ->
104
105     dumpIfSet (dopt_D_dump_parsed flags) "Parser" (ppr rdr_module) >>
106
107     dumpIfSet (dopt_D_source_stats flags) "Source Statistics"
108         (ppSourceStats False rdr_module)                >>
109
110     -- UniqueSupplies for later use (these are the only lower case uniques)
111     mkSplitUniqSupply 'd'       >>= \ ds_uniqs  -> -- desugarer
112     mkSplitUniqSupply 'r'       >>= \ ru_uniqs  -> -- rules
113     mkSplitUniqSupply 'c'       >>= \ c2s_uniqs -> -- core-to-stg
114     mkSplitUniqSupply 'u'       >>= \ tidy_uniqs -> -- tidy up
115     mkSplitUniqSupply 'g'       >>= \ st_uniqs  -> -- stg-to-stg passes
116     mkSplitUniqSupply 'n'       >>= \ ncg_uniqs -> -- native-code generator
117
118         --------------------------  Rename  ----------------
119     show_pass "Renamer"                         >>
120     _scc_     "Renamer"
121
122     renameModule rn_uniqs rdr_module            >>= \ maybe_rn_stuff ->
123     case maybe_rn_stuff of {
124         Nothing ->      -- Hurrah!  Renamer reckons that there's no need to
125                         -- go any further
126                         reportCompile mod_name "Compilation NOT required!" >>
127                         return ();
128         
129         Just (this_mod, rn_mod, 
130               old_iface, new_iface,
131               rn_name_supply, fixity_env,
132               imported_modules) ->
133                         -- Oh well, we've got to recompile for real
134
135
136         --------------------------  Typechecking ----------------
137     show_pass "TypeCheck"                               >>
138     _scc_     "TypeCheck"
139     typecheckModule dflags mod pcs hst hit pit rn_mod
140     --                tc_uniqs rn_name_supply
141     --              fixity_env rn_mod           
142                                                 >>= \ maybe_tc_stuff ->
143     case maybe_tc_stuff of {
144         Nothing -> ghcExit 1;   -- Type checker failed
145
146         Just (tc_results@(TcResults {tc_tycons  = local_tycons, 
147                                      tc_classes = local_classes, 
148                                      tc_insts   = inst_info })) ->
149
150
151         --------------------------  Desugaring ----------------
152     _scc_     "DeSugar"
153     deSugar this_mod ds_uniqs tc_results        >>= \ (desugared, rules, h_code, c_code, fe_binders) ->
154
155
156         --------------------------  Main Core-language transformations ----------------
157     _scc_     "Core2Core"
158     core2core core_cmds desugared rules         >>= \ (simplified, orphan_rules) ->
159
160         -- Do the final tidy-up
161     tidyCorePgm tidy_uniqs this_mod
162                 simplified orphan_rules         >>= \ (tidy_binds, tidy_orphan_rules) -> 
163
164         -- Run the occurrence analyser one last time, so that
165         -- dead binders get dead-binder info.  This is exploited by
166         -- code generators to avoid spitting out redundant bindings.
167         -- The occurrence-zapping in Simplify.simplCaseBinder means
168         -- that the Simplifier nukes useful dead-var stuff especially
169         -- in case patterns.
170     let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds in
171
172     coreBindsSize occ_anal_tidy_binds `seq`
173 --      TEMP: the above call zaps some space usage allocated by the
174 --      simplifier, which for reasons I don't understand, persists
175 --      thoroughout code generation
176
177
178
179         --------------------------  Convert to STG code -------------------------------
180     show_pass "Core2Stg"                        >>
181     _scc_     "Core2Stg"
182     let
183         stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
184     in
185
186         --------------------------  Simplify STG code -------------------------------
187     show_pass "Stg2Stg"                          >>
188     _scc_     "Stg2Stg"
189     stg2stg stg_cmds this_mod st_uniqs stg_binds >>= \ (stg_binds2, cost_centre_info) ->
190
191 #ifdef GHCI
192     runStgI local_tycons local_classes 
193                          (map fst stg_binds2)    >>= \ i_result ->
194     putStr ("\nANSWER = " ++ show i_result ++ "\n\n")
195     >>
196
197 #else
198         --------------------------  Interface file -------------------------------
199         -- Dump instance decls and type signatures into the interface file
200     _scc_     "Interface"
201     let
202         final_ids = collectFinalStgBinders (map fst stg_binds2)
203     in
204     writeIface this_mod old_iface new_iface
205                local_tycons local_classes inst_info
206                final_ids occ_anal_tidy_binds tidy_orphan_rules          >>
207
208
209         --------------------------  Code generation -------------------------------
210     show_pass "CodeGen"                         >>
211     _scc_     "CodeGen"
212     codeGen this_mod imported_modules
213             cost_centre_info
214             fe_binders
215             local_tycons local_classes 
216             stg_binds2                          >>= \ abstractC ->
217
218
219         --------------------------  Code output -------------------------------
220     show_pass "CodeOutput"                              >>
221     _scc_     "CodeOutput"
222     codeOutput this_mod local_tycons local_classes
223                occ_anal_tidy_binds stg_binds2
224                c_code h_code abstractC 
225                ncg_uniqs                                >>
226
227
228         --------------------------  Final report -------------------------------
229     reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
230
231 #endif
232
233
234     ghcExit 0
235     } }
236   where
237     -------------------------------------------------------------
238     -- ****** help functions:
239
240     show_pass
241       = if opt_D_show_passes
242         then \ what -> hPutStr stderr ("*** "++what++":\n")
243         else \ what -> return ()
244 \end{code}
245
246
247 %************************************************************************
248 %*                                                                      *
249 \subsection{Initial persistent state}
250 %*                                                                      *
251 %************************************************************************
252
253 \begin{code}
254 initPersistentCompilerState :: PersistentCompilerState
255 initPersistentCompilerState 
256   = PCS { pcs_PST   = initPackageDetails,
257           pcs_insts = emptyInstEnv,
258           pcs_rules = initRules,
259           pcs_PRS   = initPersistentRenamerState }
260
261 initPackageDetails :: PackageSymbolTable
262 initPackageDetails = extendTypeEnv emptyModuleEnv wiredInThings
263
264 initPersistentRenamerState :: PersistentRenamerState
265   = PRS { prsOrig  = Orig { origNames  = initOrigNames,
266                             origIParam = emptyFM },
267           prsDecls = emptyNameEnv,
268           prsInsts = emptyBag,
269           prsRules = emptyBag
270     }
271
272 initOrigNames :: FiniteMap (ModuleName,OccName) Name
273 initOrigNames = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
274               where
275                 grab names   = foldl add emptyFM names
276                 add env name = addToFM env (moduleName (nameModule name), nameOccName name) name
277
278
279 initRules :: RuleEnv
280 initRules = foldl add emptyVarEnv builtinRules
281           where
282             add env (name,rule) = extendNameEnv_C add1 env name [rule]
283             add1 rules _        = rule : rules
284 \end{code}