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