[project @ 2000-10-26 10:23:37 by sewardj]
[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 Maybe            ( isJust )
12 import Monad            ( when )
13 import IO               ( hPutStr, hPutStrLn, hClose, stderr, 
14                           openFile, IOMode(..) )
15 import HsSyn
16
17 import RdrHsSyn         ( RdrNameHsModule )
18 import FastString       ( unpackFS )
19 import StringBuffer     ( hGetStringBuffer )
20 import Parser           ( parse )
21 import Lex              ( PState(..), ParseResult(..) )
22 import SrcLoc           ( mkSrcLoc )
23
24 import Rename           ( renameModule, checkOldIface, closeIfaceDecls )
25
26 import Rules            ( emptyRuleBase )
27 import PrelInfo         ( wiredInThings )
28 import PrelNames        ( knownKeyNames )
29 import PrelRules        ( builtinRules )
30 import MkIface          ( completeIface, mkModDetailsFromIface, mkModDetails,
31                           writeIface )
32 import TcModule         ( TcResults(..), typecheckModule )
33 import TcEnv            ( tcEnvTyCons, tcEnvClasses )
34 import InstEnv          ( emptyInstEnv )
35 import Desugar          ( deSugar )
36 import SimplCore        ( core2core )
37 import OccurAnal        ( occurAnalyseBinds )
38 import CoreUtils        ( coreBindsSize )
39 import CoreTidy         ( tidyCorePgm )
40 import CoreToStg        ( topCoreBindsToStg )
41 import StgSyn           ( collectFinalStgBinders )
42 import SimplStg         ( stg2stg )
43 import CodeGen          ( codeGen )
44 import CodeOutput       ( codeOutput )
45
46 import Module           ( ModuleName, moduleNameUserString, 
47                           moduleUserString, moduleName, emptyModuleEnv )
48 import CmdLineOpts
49 import ErrUtils         ( ghcExit, doIfSet, dumpIfSet_dyn )
50 import UniqSupply       ( mkSplitUniqSupply )
51
52 import Bag              ( emptyBag )
53 import Outputable
54 import Char             ( isSpace )
55 import StgInterp        ( stgToInterpSyn )
56 import HscStats         ( ppSourceStats )
57 import HscTypes         ( ModDetails, ModIface, PersistentCompilerState(..),
58                           PersistentRenamerState(..), WhatsImported(..),
59                           HomeSymbolTable, PackageSymbolTable, ImportVersion, 
60                           GenAvailInfo(..), RdrAvailInfo, OrigNameEnv(..),
61                           PackageRuleBase, HomeIfaceTable, PackageIfaceTable,
62                           extendTypeEnv )
63 import RnMonad          ( ExportItem, ParsedIface(..) )
64 import CmSummarise      ( ModSummary(..), name_of_summary, ms_get_imports )
65 import Finder           ( Finder )
66 import InterpSyn        ( UnlinkedIBind )
67 import StgInterp        ( ItblEnv )
68 import FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
69 import OccName          ( OccName, pprOccName )
70 import Name             ( Name, nameModule, emptyNameEnv, nameOccName, 
71                           getName, extendNameEnv_C )
72 import VarEnv           ( emptyVarEnv )
73 \end{code}
74
75
76 %************************************************************************
77 %*                                                                      *
78 \subsection{The main compiler pipeline}
79 %*                                                                      *
80 %************************************************************************
81
82 \begin{code}
83 data HscResult
84    = HscOK   ModDetails              -- new details (HomeSymbolTable additions)
85              (Maybe ModIface)        -- new iface (if any compilation was done)
86              (Maybe String)          -- generated stub_h filename (in /tmp)
87              (Maybe String)          -- generated stub_c filename (in /tmp)
88              (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
89              PersistentCompilerState -- updated PCS
90
91    | HscFail PersistentCompilerState -- updated PCS
92         -- no errors or warnings; the individual passes
93         -- (parse/rename/typecheck) print messages themselves
94
95 hscMain
96   :: DynFlags
97   -> Finder
98   -> ModSummary       -- summary, including source filename
99   -> Maybe ModIface   -- old interface, if available
100   -> String           -- file in which to put the output (.s, .hc, .java etc.)
101   -> [CoreToDo]
102   -> [StgToDo]
103   -> HomeSymbolTable            -- for home module ModDetails
104   -> HomeIfaceTable
105   -> PackageIfaceTable
106   -> PersistentCompilerState    -- IN: persistent compiler state
107   -> IO HscResult
108
109 hscMain dflags finder summary maybe_old_iface output_filename
110         core_cmds stg_cmds hst hit pit pcs
111  = do {
112       -- ????? source_unchanged :: Bool -- extracted from summary?
113       let source_unchanged = trace "WARNING: source_unchanged?!" False
114       ;
115       (pcs_ch, check_errs, (recomp_reqd, maybe_checked_iface))
116          <- checkOldIface dflags finder hit hst pcs (ms_mod summary)
117                           source_unchanged maybe_old_iface;
118       if check_errs then
119          return (HscFail pcs_ch)
120       else do {
121
122       let no_old_iface = not (isJust maybe_checked_iface)
123           what_next | recomp_reqd || no_old_iface = hscRecomp 
124                     | otherwise                   = hscNoRecomp
125       ;
126       what_next dflags finder summary maybe_checked_iface output_filename
127                 core_cmds stg_cmds hst hit pit pcs_ch
128       }}
129
130
131 hscNoRecomp dflags finder summary maybe_checked_iface output_filename
132             core_cmds stg_cmds hst hit pit pcs_ch
133  = do {
134       -- we definitely expect to have the old interface available
135       let old_iface = case maybe_checked_iface of 
136                          Just old_if -> old_if
137                          Nothing -> panic "hscNoRecomp:old_iface"
138       ;
139       -- CLOSURE
140       (pcs_cl, closure_errs, cl_hs_decls) 
141          <- closeIfaceDecls dflags finder hit hst pcs_ch old_iface ;
142       if closure_errs then 
143          return (HscFail pcs_cl) 
144       else do {
145
146       -- TYPECHECK
147       maybe_tc_result
148          <- typecheckModule dflags (ms_mod summary) pcs_cl hst hit cl_hs_decls;
149       case maybe_tc_result of {
150          Nothing -> return (HscFail pcs_cl);
151          Just tc_result -> do {
152
153       let pcs_tc        = tc_pcs tc_result
154           env_tc        = tc_env tc_result
155           binds_tc      = tc_binds tc_result
156           local_insts   = tc_insts tc_result
157           local_rules   = tc_rules tc_result
158       ;
159       -- create a new details from the closed, typechecked, old iface
160       let new_details = mkModDetailsFromIface env_tc local_insts local_rules
161       ;
162       return (HscOK new_details
163                     Nothing -- tells CM to use old iface and linkables
164                     Nothing Nothing -- foreign export stuff
165                     Nothing -- ibinds
166                     pcs_tc)
167       }}}}
168
169
170 hscRecomp dflags finder summary maybe_checked_iface output_filename
171           core_cmds stg_cmds hst hit pit pcs_ch
172  = do {
173       -- what target are we shooting for?
174       let toInterp = dopt_HscLang dflags == HscInterpreted
175           this_mod = ms_mod summary
176       ;
177       -- PARSE
178       maybe_parsed <- myParseModule dflags summary;
179       case maybe_parsed of {
180          Nothing -> return (HscFail pcs_ch);
181          Just rdr_module -> do {
182
183       -- RENAME
184       show_pass dflags "Renamer";
185       (pcs_rn, maybe_rn_result) 
186          <- renameModule dflags finder hit hst pcs_ch this_mod rdr_module;
187       case maybe_rn_result of {
188          Nothing -> return (HscFail pcs_rn);
189          Just (new_iface, rn_hs_decls) -> do {
190
191       -- TYPECHECK
192       show_pass dflags "Typechecker";
193       maybe_tc_result
194          <- typecheckModule dflags this_mod pcs_rn hst hit rn_hs_decls;
195       case maybe_tc_result of {
196          Nothing -> return (HscFail pcs_rn);
197          Just tc_result -> do {
198
199       let pcs_tc        = tc_pcs tc_result
200           env_tc        = tc_env tc_result
201           binds_tc      = tc_binds tc_result
202           local_insts   = tc_insts tc_result
203       ;
204       -- DESUGAR, SIMPLIFY, TIDY-CORE
205       -- We grab the the unfoldings at this point.
206       (tidy_binds, orphan_rules, foreign_stuff)
207          <- dsThenSimplThenTidy dflags this_mod tc_result core_cmds
208       ;
209       -- CONVERT TO STG
210       (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids) 
211          <- myCoreToStg dflags this_mod tidy_binds stg_cmds
212       ;
213       -- cook up a new ModDetails now we (finally) have all the bits
214       let new_details = mkModDetails env_tc local_insts tidy_binds 
215                                      top_level_ids orphan_rules
216       ;
217       -- and possibly create a new ModIface
218       let maybe_final_iface 
219              = completeIface maybe_checked_iface new_iface new_details 
220       ;
221
222       -- Write the interface file
223       writeIface finder maybe_final_iface
224       ;
225
226       -- do the rest of code generation/emission
227       (maybe_ibinds, maybe_stub_h_filename, maybe_stub_c_filename) 
228          <- restOfCodeGeneration dflags toInterp summary
229                cost_centre_info foreign_stuff tc_env stg_binds oa_tidy_binds
230       ;
231       -- and the answer is ...
232       return (HscOK new_details maybe_final_iface 
233                     maybe_stub_h_filename maybe_stub_c_filename
234                     maybe_ibinds pcs_tc)
235       }}}}}}}
236
237
238 myParseModule dflags summary
239  = do --------------------------  Parser  ----------------
240       show_pass dflags "Parser"
241       -- _scc_     "Parser"
242
243       let src_filename -- name of the preprocessed source file
244             = case ms_ppsource summary of
245                  Just (filename, fingerprint) -> filename
246                  Nothing -> pprPanic 
247                                "myParseModule:summary is not of a source module"
248                                (ppr summary)
249
250       buf <- hGetStringBuffer True{-expand tabs-} src_filename
251
252       let glaexts | dopt Opt_GlasgowExts dflags = 1#
253                   | otherwise                 = 0#
254
255       case parse buf PState{ bol = 0#, atbol = 1#,
256                              context = [], glasgow_exts = glaexts,
257                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
258
259         PFailed err -> do { hPutStrLn stderr (showSDoc err);
260                             return Nothing };
261         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
262
263       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
264       
265       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
266                            (ppSourceStats False rdr_module) ;
267       
268       return (Just rdr_module)
269       }}
270
271
272 restOfCodeGeneration dflags toInterp summary cost_centre_info 
273                      foreign_stuff tc_env stg_binds oa_tidy_binds
274  | toInterp
275  = return (Nothing, Nothing, 
276            Just (stgToInterpSyn stg_binds local_tycons local_classes))
277  | otherwise
278  = do --------------------------  Code generation -------------------------------
279       show_pass dflags "CodeGen"
280       -- _scc_     "CodeGen"
281       abstractC <- codeGen this_mod imported_modules
282                            cost_centre_info fe_binders
283                            local_tycons local_classes stg_binds
284
285       --------------------------  Code output -------------------------------
286       show_pass dflags "CodeOutput"
287       -- _scc_     "CodeOutput"
288       ncg_uniqs <- mkSplitUniqSupply 'n'
289       (maybe_stub_h_name, maybe_stub_c_name)
290          <- codeOutput this_mod local_tycons local_classes
291                        oa_tidy_binds stg_binds
292                        c_code h_code abstractC ncg_uniqs
293
294       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
295  where
296     local_tycons     = tcEnvTyCons tc_env
297     local_classes    = tcEnvClasses tc_env
298     this_mod         = ms_mod summary
299     imported_modules = ms_get_imports summary
300     (fe_binders,h_code,c_code) = foreign_stuff
301
302
303 dsThenSimplThenTidy dflags this_mod tc_result core_cmds
304 -- make up ds_uniqs here
305  = do --------------------------  Desugaring ----------------
306       -- _scc_     "DeSugar"
307       ds_uniqs <- mkSplitUniqSupply 'd'
308       (desugared, rules, h_code, c_code, fe_binders) 
309          <- deSugar this_mod ds_uniqs tc_result
310
311       --------------------------  Main Core-language transformations ----------------
312       -- _scc_     "Core2Core"
313       (simplified, orphan_rules)  <- core2core core_cmds desugared rules
314
315       -- Do the final tidy-up
316       (tidy_binds, tidy_orphan_rules) 
317          <- tidyCorePgm this_mod simplified orphan_rules
318       
319       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
320
321
322 myCoreToStg dflags this_mod tidy_binds stg_cmds
323  = do 
324       c2s_uniqs <- mkSplitUniqSupply 'c'
325       st_uniqs  <- mkSplitUniqSupply 'g'
326       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
327
328       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
329       -- TEMP: the above call zaps some space usage allocated by the
330       -- simplifier, which for reasons I don't understand, persists
331       -- thoroughout code generation
332
333       show_pass dflags "Core2Stg"
334       -- _scc_     "Core2Stg"
335       let stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
336
337       show_pass dflags "Stg2Stg"
338       -- _scc_     "Stg2Stg"
339       (stg_binds2, cost_centre_info) <- stg2stg stg_cmds this_mod st_uniqs stg_binds
340       let final_ids = collectFinalStgBinders (map fst stg_binds2)
341
342       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
343
344
345 show_pass dflags what
346   = if   dopt Opt_D_show_passes dflags
347     then hPutStr stderr ("*** "++what++":\n")
348     else return ()
349 \end{code}
350
351
352 %************************************************************************
353 %*                                                                      *
354 \subsection{Initial persistent state}
355 %*                                                                      *
356 %************************************************************************
357
358 \begin{code}
359 initPersistentCompilerState :: IO PersistentCompilerState
360 initPersistentCompilerState 
361   = do prs <- initPersistentRenamerState
362        return (
363         PCS { pcs_PST   = initPackageDetails,
364               pcs_insts = emptyInstEnv,
365               pcs_rules = emptyRuleBase,
366               pcs_PRS   = prs
367             }
368         )
369
370 initPackageDetails :: PackageSymbolTable
371 initPackageDetails = extendTypeEnv emptyModuleEnv wiredInThings
372
373 initPersistentRenamerState :: IO PersistentRenamerState
374   = do ns <- mkSplitUniqSupply 'r'
375        return (
376         PRS { prsOrig  = Orig { origNames  = initOrigNames,
377                                 origIParam = emptyFM },
378               prsDecls = emptyNameEnv,
379               prsInsts = emptyBag,
380               prsRules = emptyBag,
381               prsNS    = ns
382             }
383         )
384
385 initOrigNames :: FiniteMap (ModuleName,OccName) Name
386 initOrigNames = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
387               where
388                 grab names   = foldl add emptyFM names
389                 add env name = addToFM env (moduleName (nameModule name), nameOccName name) name
390
391
392 initRules :: PackageRuleBase
393 initRules = foldl add emptyVarEnv builtinRules
394           where
395             add env (name,rule) 
396                = extendNameEnv_C (\rules _ -> rule:rules) 
397                                  env name [rule]
398 \end{code}