[project @ 2000-10-27 13:50:25 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 ( 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, emptyIfaceTable )
66 import RnMonad          ( ExportItem, ParsedIface(..) )
67 import CmSummarise      ( ModSummary(..), name_of_summary, ms_get_imports,
68                           mimp_name )
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   -> ModSummary       -- summary, including source filename
103   -> Maybe ModIface   -- old interface, if available
104   -> HomeSymbolTable            -- for home module ModDetails
105   -> HomeIfaceTable
106   -> PersistentCompilerState    -- IN: persistent compiler state
107   -> IO HscResult
108
109 hscMain dflags summary maybe_old_iface hst hit pcs
110  = do {
111       -- ????? source_unchanged :: Bool -- extracted from summary?
112       let source_unchanged = trace "WARNING: source_unchanged?!" False
113       ;
114       putStrLn "checking old iface ...";
115       (pcs_ch, check_errs, (recomp_reqd, maybe_checked_iface))
116          <- checkOldIface dflags 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       putStrLn "doing what_next ...";
127       what_next dflags summary maybe_checked_iface
128                 hst hit pcs_ch
129       }}
130
131
132 hscNoRecomp dflags summary maybe_checked_iface hst hit 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 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 summary maybe_checked_iface hst hit 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 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       -- Write the interface file
224       writeIface maybe_final_iface
225       ;
226       -- do the rest of code generation/emission
227       (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
228          <- restOfCodeGeneration dflags toInterp summary
229                cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
230                hit (pcs_PIT pcs_tc)       
231       ;
232       -- and the answer is ...
233       return (HscOK new_details maybe_final_iface 
234                     maybe_stub_h_filename maybe_stub_c_filename
235                     maybe_ibinds pcs_tc)
236       }}}}}}}
237
238
239 myParseModule dflags summary
240  = do --------------------------  Parser  ----------------
241       show_pass dflags "Parser"
242       -- _scc_     "Parser"
243
244       let src_filename -- name of the preprocessed source file
245             = case ms_ppsource summary of
246                  Just (filename, fingerprint) -> filename
247                  Nothing -> pprPanic 
248                                "myParseModule:summary is not of a source module"
249                                (ppr summary)
250
251       buf <- hGetStringBuffer True{-expand tabs-} src_filename
252
253       let glaexts | dopt Opt_GlasgowExts dflags = 1#
254                   | otherwise                 = 0#
255
256       case parse buf PState{ bol = 0#, atbol = 1#,
257                              context = [], glasgow_exts = glaexts,
258                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
259
260         PFailed err -> do { hPutStrLn stderr (showSDoc err);
261                             return Nothing };
262         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
263
264       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
265       
266       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
267                            (ppSourceStats False rdr_module) ;
268       
269       return (Just rdr_module)
270       }}
271
272
273 restOfCodeGeneration dflags toInterp summary cost_centre_info 
274                      foreign_stuff env_tc stg_binds oa_tidy_binds
275                      hit pit -- these last two for mapping ModNames to Modules
276  | toInterp
277  = do (ibinds,itbl_env) 
278          <- stgToInterpSyn (map fst stg_binds) local_tycons local_classes
279       return (Nothing, Nothing, Just (ibinds,itbl_env))
280  | otherwise
281  = do --------------------------  Code generation -------------------------------
282       show_pass dflags "CodeGen"
283       -- _scc_     "CodeGen"
284       abstractC <- codeGen dflags this_mod imported_modules
285                            cost_centre_info fe_binders
286                            local_tycons local_classes stg_binds
287
288       --------------------------  Code output -------------------------------
289       show_pass dflags "CodeOutput"
290       -- _scc_     "CodeOutput"
291       ncg_uniqs <- mkSplitUniqSupply 'n'
292       (maybe_stub_h_name, maybe_stub_c_name)
293          <- codeOutput dflags this_mod local_tycons local_classes
294                        oa_tidy_binds stg_binds
295                        c_code h_code abstractC ncg_uniqs
296
297       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
298  where
299     local_tycons     = typeEnvTyCons env_tc
300     local_classes    = typeEnvClasses env_tc
301     this_mod         = ms_mod summary
302     imported_modules = map (mod_name_to_Module.mimp_name) 
303                            (ms_get_imports summary)
304     (fe_binders,h_code,c_code) = foreign_stuff
305
306     mod_name_to_Module :: ModuleName -> Module
307     mod_name_to_Module nm
308        = let str_mi = case lookupModuleEnvByName hit nm of
309                           Just mi -> mi
310                           Nothing -> case lookupModuleEnvByName pit nm of
311                                         Just mi -> mi
312                                         Nothing -> barf nm
313          in  mi_module str_mi
314     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
315                        (ppr nm)
316
317
318 dsThenSimplThenTidy dflags rule_base this_mod tc_result hst
319  = do --------------------------  Desugaring ----------------
320       -- _scc_     "DeSugar"
321       show_pass dflags "DeSugar"
322       ds_uniqs <- mkSplitUniqSupply 'd'
323       (desugared, rules, h_code, c_code, fe_binders) 
324          <- deSugar dflags this_mod ds_uniqs hst tc_result
325
326       --------------------------  Main Core-language transformations ----------------
327       -- _scc_     "Core2Core"
328       show_pass dflags "Core2Core"
329       (simplified, orphan_rules) 
330          <- core2core dflags rule_base hst desugared rules
331
332       -- Do the final tidy-up
333       show_pass dflags "CoreTidy"
334       (tidy_binds, tidy_orphan_rules) 
335          <- tidyCorePgm dflags this_mod simplified orphan_rules
336       
337       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
338
339
340 myCoreToStg dflags this_mod tidy_binds
341  = do 
342       c2s_uniqs <- mkSplitUniqSupply 'c'
343       st_uniqs  <- mkSplitUniqSupply 'g'
344       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
345
346       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
347       -- TEMP: the above call zaps some space usage allocated by the
348       -- simplifier, which for reasons I don't understand, persists
349       -- thoroughout code generation
350
351       show_pass dflags "Core2Stg"
352       -- _scc_     "Core2Stg"
353       let stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
354
355       show_pass dflags "Stg2Stg"
356       -- _scc_     "Stg2Stg"
357       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
358       let final_ids = collectFinalStgBinders (map fst stg_binds2)
359
360       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
361
362
363 show_pass dflags what
364   = if   dopt Opt_D_show_passes dflags
365     then hPutStr stderr ("*** "++what++":\n")
366     else return ()
367 \end{code}
368
369
370 %************************************************************************
371 %*                                                                      *
372 \subsection{Initial persistent state}
373 %*                                                                      *
374 %************************************************************************
375
376 \begin{code}
377 initPersistentCompilerState :: IO PersistentCompilerState
378 initPersistentCompilerState 
379   = do prs <- initPersistentRenamerState
380        return (
381         PCS { pcs_PIT   = emptyIfaceTable,
382               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}