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