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