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