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