[project @ 2000-10-26 14:34:57 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                           extendModuleEnv )
49 import CmdLineOpts
50 import ErrUtils         ( ghcExit, doIfSet, dumpIfSet_dyn )
51 import UniqSupply       ( mkSplitUniqSupply )
52
53 import Bag              ( emptyBag )
54 import Outputable
55 import Char             ( isSpace )
56 import StgInterp        ( stgToInterpSyn )
57 import HscStats         ( ppSourceStats )
58 import HscTypes         ( ModDetails, ModIface(..), PersistentCompilerState(..),
59                           PersistentRenamerState(..), WhatsImported(..),
60                           HomeSymbolTable, PackageSymbolTable, ImportVersion, 
61                           GenAvailInfo(..), RdrAvailInfo, OrigNameEnv(..),
62                           PackageRuleBase, HomeIfaceTable, PackageIfaceTable,
63                           extendTypeEnv, groupTyThings, TypeEnv, TyThing,
64                           typeEnvClasses, typeEnvTyCons )
65 import RnMonad          ( ExportItem, ParsedIface(..) )
66 import CmSummarise      ( ModSummary(..), name_of_summary, ms_get_imports,
67                           mimp_name )
68 import Finder           ( Finder )
69 import InterpSyn        ( UnlinkedIBind )
70 import StgInterp        ( ItblEnv )
71 import FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
72 import OccName          ( OccName, pprOccName )
73 import Name             ( Name, nameModule, emptyNameEnv, nameOccName, 
74                           getName, extendNameEnv_C, nameEnvElts )
75 import VarEnv           ( emptyVarEnv )
76 import Module           ( Module, mkModuleName, lookupModuleEnvByName )
77
78 \end{code}
79
80
81 %************************************************************************
82 %*                                                                      *
83 \subsection{The main compiler pipeline}
84 %*                                                                      *
85 %************************************************************************
86
87 \begin{code}
88 data HscResult
89    = HscOK   ModDetails              -- new details (HomeSymbolTable additions)
90              (Maybe ModIface)        -- new iface (if any compilation was done)
91              (Maybe String)          -- generated stub_h filename (in /tmp)
92              (Maybe String)          -- generated stub_c filename (in /tmp)
93              (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
94              PersistentCompilerState -- updated PCS
95
96    | HscFail PersistentCompilerState -- updated PCS
97         -- no errors or warnings; the individual passes
98         -- (parse/rename/typecheck) print messages themselves
99
100 hscMain
101   :: DynFlags
102   -> Finder
103   -> ModSummary       -- summary, including source filename
104   -> Maybe ModIface   -- old interface, if available
105   -> HomeSymbolTable            -- for home module ModDetails
106   -> HomeIfaceTable
107   -> PackageIfaceTable
108   -> PersistentCompilerState    -- IN: persistent compiler state
109   -> IO HscResult
110
111 hscMain dflags finder summary maybe_old_iface hst hit pit pcs
112  = do {
113       -- ????? source_unchanged :: Bool -- extracted from summary?
114       let source_unchanged = trace "WARNING: source_unchanged?!" False
115       ;
116       (pcs_ch, check_errs, (recomp_reqd, maybe_checked_iface))
117          <- checkOldIface dflags finder hit hst pcs (ms_mod summary)
118                           source_unchanged maybe_old_iface;
119       if check_errs then
120          return (HscFail pcs_ch)
121       else do {
122
123       let no_old_iface = not (isJust maybe_checked_iface)
124           what_next | recomp_reqd || no_old_iface = hscRecomp 
125                     | otherwise                   = hscNoRecomp
126       ;
127       what_next dflags finder summary maybe_checked_iface
128                 hst hit pit pcs_ch
129       }}
130
131
132 hscNoRecomp dflags finder summary maybe_checked_iface 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 hst hit pit pcs_ch
171  = do {
172       -- what target are we shooting for?
173       let toInterp = dopt_HscLang dflags == HscInterpreted
174           this_mod = ms_mod summary
175       ;
176       -- PARSE
177       maybe_parsed <- myParseModule dflags summary;
178       case maybe_parsed of {
179          Nothing -> return (HscFail pcs_ch);
180          Just rdr_module -> do {
181
182       -- RENAME
183       show_pass dflags "Renamer";
184       (pcs_rn, maybe_rn_result) 
185          <- renameModule dflags finder hit hst pcs_ch this_mod rdr_module;
186       case maybe_rn_result of {
187          Nothing -> return (HscFail pcs_rn);
188          Just (new_iface, rn_hs_decls) -> do {
189
190       -- TYPECHECK
191       show_pass dflags "Typechecker";
192       maybe_tc_result
193          <- typecheckModule dflags this_mod pcs_rn hst hit rn_hs_decls;
194       case maybe_tc_result of {
195          Nothing -> return (HscFail pcs_rn);
196          Just tc_result -> do {
197
198       let pcs_tc        = tc_pcs tc_result
199           env_tc        = tc_env tc_result
200           binds_tc      = tc_binds tc_result
201           local_insts   = tc_insts tc_result
202       ;
203       -- DESUGAR, SIMPLIFY, TIDY-CORE
204       -- We grab the the unfoldings at this point.
205       (tidy_binds, orphan_rules, foreign_stuff)
206          <- dsThenSimplThenTidy dflags (pcs_rules pcs_tc) this_mod tc_result hst
207       ;
208       -- CONVERT TO STG
209       (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids) 
210          <- myCoreToStg dflags this_mod tidy_binds
211       ;
212       -- cook up a new ModDetails now we (finally) have all the bits
213       let new_details = mkModDetails env_tc local_insts tidy_binds 
214                                      top_level_ids orphan_rules
215       ;
216       -- and possibly create a new ModIface
217       let maybe_final_iface_and_sdoc 
218              = completeIface maybe_checked_iface new_iface new_details 
219           maybe_final_iface
220              = case maybe_final_iface_and_sdoc of 
221                   Just (fif, sdoc) -> Just fif; Nothing -> Nothing
222       ;
223       -- SimonM does this, higher up
224       -- -- Write the interface file
225       -- writeIface finder maybe_final_iface
226       -- ;
227       -- do the rest of code generation/emission
228       (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
229          <- restOfCodeGeneration dflags toInterp summary
230                cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
231                hit (pcs_PIT pcs_tc)       
232       ;
233       -- and the answer is ...
234       return (HscOK new_details maybe_final_iface 
235                     maybe_stub_h_filename maybe_stub_c_filename
236                     maybe_ibinds pcs_tc)
237       }}}}}}}
238
239
240 myParseModule dflags summary
241  = do --------------------------  Parser  ----------------
242       show_pass dflags "Parser"
243       -- _scc_     "Parser"
244
245       let src_filename -- name of the preprocessed source file
246             = case ms_ppsource summary of
247                  Just (filename, fingerprint) -> filename
248                  Nothing -> pprPanic 
249                                "myParseModule:summary is not of a source module"
250                                (ppr summary)
251
252       buf <- hGetStringBuffer True{-expand tabs-} src_filename
253
254       let glaexts | dopt Opt_GlasgowExts dflags = 1#
255                   | otherwise                 = 0#
256
257       case parse buf PState{ bol = 0#, atbol = 1#,
258                              context = [], glasgow_exts = glaexts,
259                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
260
261         PFailed err -> do { hPutStrLn stderr (showSDoc err);
262                             return Nothing };
263         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
264
265       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
266       
267       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
268                            (ppSourceStats False rdr_module) ;
269       
270       return (Just rdr_module)
271       }}
272
273
274 restOfCodeGeneration dflags toInterp summary cost_centre_info 
275                      foreign_stuff env_tc stg_binds oa_tidy_binds
276                      hit pit -- these last two for mapping ModNames to Modules
277  | toInterp
278  = do (ibinds,itbl_env) 
279          <- stgToInterpSyn (map fst stg_binds) local_tycons local_classes
280       return (Nothing, Nothing, Just (ibinds,itbl_env))
281  | otherwise
282  = do --------------------------  Code generation -------------------------------
283       show_pass dflags "CodeGen"
284       -- _scc_     "CodeGen"
285       abstractC <- codeGen dflags this_mod imported_modules
286                            cost_centre_info fe_binders
287                            local_tycons local_classes stg_binds
288
289       --------------------------  Code output -------------------------------
290       show_pass dflags "CodeOutput"
291       -- _scc_     "CodeOutput"
292       ncg_uniqs <- mkSplitUniqSupply 'n'
293       (maybe_stub_h_name, maybe_stub_c_name)
294          <- codeOutput dflags this_mod local_tycons local_classes
295                        oa_tidy_binds stg_binds
296                        c_code h_code abstractC ncg_uniqs
297
298       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
299  where
300     local_tycons     = typeEnvTyCons env_tc
301     local_classes    = typeEnvClasses env_tc
302     this_mod         = ms_mod summary
303     imported_modules = map (mod_name_to_Module.mimp_name) 
304                            (ms_get_imports summary)
305     (fe_binders,h_code,c_code) = foreign_stuff
306
307     mod_name_to_Module :: ModuleName -> Module
308     mod_name_to_Module nm
309        = let str_mi = case lookupModuleEnvByName hit nm of
310                           Just mi -> mi
311                           Nothing -> case lookupModuleEnvByName pit nm of
312                                         Just mi -> mi
313                                         Nothing -> barf nm
314          in  mi_module str_mi
315     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
316                        (ppr nm)
317
318
319 dsThenSimplThenTidy dflags rule_base this_mod tc_result hst
320  = do --------------------------  Desugaring ----------------
321       -- _scc_     "DeSugar"
322       show_pass dflags "DeSugar"
323       ds_uniqs <- mkSplitUniqSupply 'd'
324       (desugared, rules, h_code, c_code, fe_binders) 
325          <- deSugar dflags this_mod ds_uniqs hst tc_result
326
327       --------------------------  Main Core-language transformations ----------------
328       -- _scc_     "Core2Core"
329       show_pass dflags "Core2Core"
330       (simplified, orphan_rules) 
331          <- core2core dflags rule_base hst desugared rules
332
333       -- Do the final tidy-up
334       show_pass dflags "CoreTidy"
335       (tidy_binds, tidy_orphan_rules) 
336          <- tidyCorePgm dflags this_mod simplified orphan_rules
337       
338       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
339
340
341 myCoreToStg dflags this_mod tidy_binds
342  = do 
343       c2s_uniqs <- mkSplitUniqSupply 'c'
344       st_uniqs  <- mkSplitUniqSupply 'g'
345       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
346
347       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
348       -- TEMP: the above call zaps some space usage allocated by the
349       -- simplifier, which for reasons I don't understand, persists
350       -- thoroughout code generation
351
352       show_pass dflags "Core2Stg"
353       -- _scc_     "Core2Stg"
354       let stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
355
356       show_pass dflags "Stg2Stg"
357       -- _scc_     "Stg2Stg"
358       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
359       let final_ids = collectFinalStgBinders (map fst stg_binds2)
360
361       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
362
363
364 show_pass dflags what
365   = if   dopt Opt_D_show_passes dflags
366     then hPutStr stderr ("*** "++what++":\n")
367     else return ()
368 \end{code}
369
370
371 %************************************************************************
372 %*                                                                      *
373 \subsection{Initial persistent state}
374 %*                                                                      *
375 %************************************************************************
376
377 \begin{code}
378 initPersistentCompilerState :: IO PersistentCompilerState
379 initPersistentCompilerState 
380   = do prs <- initPersistentRenamerState
381        return (
382         PCS { pcs_PST   = initPackageDetails,
383               pcs_insts = emptyInstEnv,
384               pcs_rules = emptyRuleBase,
385               pcs_PRS   = prs
386             }
387         )
388
389 initPackageDetails :: PackageSymbolTable
390 initPackageDetails = extendTypeEnv emptyModuleEnv (groupTyThings wiredInThings)
391
392 --initPackageDetails = panic "initPackageDetails"
393
394 initPersistentRenamerState :: IO PersistentRenamerState
395   = do ns <- mkSplitUniqSupply 'r'
396        return (
397         PRS { prsOrig  = Orig { origNames  = initOrigNames,
398                                 origIParam = emptyFM },
399               prsDecls = emptyNameEnv,
400               prsInsts = emptyBag,
401               prsRules = emptyBag,
402               prsNS    = ns
403             }
404         )
405
406 initOrigNames :: FiniteMap (ModuleName,OccName) Name
407 initOrigNames 
408    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
409      where
410         grab names = foldl add emptyFM names
411         add env name 
412            = addToFM env (moduleName (nameModule name), nameOccName name) name
413
414
415 initRules :: PackageRuleBase
416 initRules = emptyRuleBase
417 {- SHOULD BE (ish)
418             foldl add emptyVarEnv builtinRules
419           where
420             add env (name,rule) 
421               = extendRuleBase env name rule
422 -}
423 \end{code}