[project @ 2000-10-30 18:13:15 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         ( 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 Util             ( unJust )
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(..), ModuleLocation(..),
53                           HomeSymbolTable, 
54                           OrigNameEnv(..), PackageRuleBase, HomeIfaceTable, 
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 ( "hscMain: location =\n" ++ show location);
98       putStrLn "checking old iface ...";
99       (pcs_ch, check_errs, (recomp_reqd, maybe_checked_iface))
100          <- checkOldIface dflags hit hst pcs (unJust (ml_hi_file location) "hscMain")
101                           source_unchanged maybe_old_iface;
102       if check_errs then
103          return (HscFail pcs_ch)
104       else do {
105
106       let no_old_iface = not (isJust maybe_checked_iface)
107           what_next | recomp_reqd || no_old_iface = hscRecomp 
108                     | otherwise                   = hscNoRecomp
109       ;
110       putStrLn "doing what_next ...";
111       what_next dflags location maybe_checked_iface
112                 hst hit pcs_ch
113       }}
114
115
116 hscNoRecomp dflags location maybe_checked_iface hst hit pcs_ch
117  = do {
118       -- we definitely expect to have the old interface available
119       let old_iface = case maybe_checked_iface of 
120                          Just old_if -> old_if
121                          Nothing -> panic "hscNoRecomp:old_iface"
122           this_mod = mi_module old_iface
123       ;
124       -- CLOSURE
125       (pcs_cl, closure_errs, cl_hs_decls) 
126          <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
127       if closure_errs then 
128          return (HscFail pcs_cl) 
129       else do {
130
131       -- TYPECHECK
132       maybe_tc_result
133          <- typecheckModule dflags this_mod pcs_cl hst hit cl_hs_decls;
134       case maybe_tc_result of {
135          Nothing -> return (HscFail pcs_cl);
136          Just tc_result -> do {
137
138       let pcs_tc      = tc_pcs tc_result
139           env_tc      = tc_env tc_result
140           local_insts = tc_insts tc_result
141           local_rules = tc_rules tc_result
142       ;
143       -- create a new details from the closed, typechecked, old iface
144       let new_details = mkModDetailsFromIface env_tc local_insts local_rules
145       ;
146       return (HscOK new_details
147                     Nothing -- tells CM to use old iface and linkables
148                     Nothing Nothing -- foreign export stuff
149                     Nothing -- ibinds
150                     pcs_tc)
151       }}}}
152
153
154 hscRecomp dflags location maybe_checked_iface hst hit pcs_ch
155  = do {
156       -- what target are we shooting for?
157       let toInterp = dopt_HscLang dflags == HscInterpreted
158       ;
159 --      putStrLn ("toInterp = " ++ show toInterp);
160       -- PARSE
161       maybe_parsed 
162          <- myParseModule dflags (unJust (ml_hspp_file location) "hscRecomp:hspp");
163       case maybe_parsed of {
164          Nothing -> return (HscFail pcs_ch);
165          Just rdr_module -> do {
166
167       -- RENAME
168       let this_mod = mkModuleInThisPackage (hsModuleName rdr_module)
169       ;
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 (unJust (ml_hi_file location) "hscRecomp:hi") 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 this_mod
216                (map ideclName (hsModuleImports rdr_module))
217                cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
218                hit (pcs_PIT pcs_tc)       
219       ;
220       -- and the answer is ...
221       return (HscOK new_details maybe_final_iface 
222                     maybe_stub_h_filename maybe_stub_c_filename
223                     maybe_ibinds pcs_tc)
224       }}}}}}}
225
226
227 myParseModule dflags src_filename
228  = do --------------------------  Parser  ----------------
229       show_pass dflags "Parser"
230       -- _scc_     "Parser"
231
232       buf <- hGetStringBuffer True{-expand tabs-} src_filename
233
234       let glaexts | dopt Opt_GlasgowExts dflags = 1#
235                   | otherwise                 = 0#
236
237       case parse buf PState{ bol = 0#, atbol = 1#,
238                              context = [], glasgow_exts = glaexts,
239                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
240
241         PFailed err -> do { hPutStrLn stderr (showSDoc err);
242                             return Nothing };
243         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
244
245       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
246       
247       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
248                            (ppSourceStats False rdr_module) ;
249       
250       return (Just rdr_module)
251       }}
252
253
254 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info 
255                      foreign_stuff env_tc stg_binds oa_tidy_binds
256                      hit pit -- these last two for mapping ModNames to Modules
257  | toInterp
258  = do (ibinds,itbl_env) 
259          <- stgToInterpSyn (map fst stg_binds) local_tycons local_classes
260       return (Nothing, Nothing, Just (ibinds,itbl_env))
261  | otherwise
262  = do --------------------------  Code generation -------------------------------
263       show_pass dflags "CodeGen"
264       -- _scc_     "CodeGen"
265       abstractC <- codeGen dflags this_mod imported_modules
266                            cost_centre_info fe_binders
267                            local_tycons local_classes stg_binds
268
269       --------------------------  Code output -------------------------------
270       show_pass dflags "CodeOutput"
271       -- _scc_     "CodeOutput"
272       ncg_uniqs <- mkSplitUniqSupply 'n'
273       (maybe_stub_h_name, maybe_stub_c_name)
274          <- codeOutput dflags this_mod local_tycons local_classes
275                        oa_tidy_binds stg_binds
276                        c_code h_code abstractC ncg_uniqs
277
278       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
279  where
280     local_tycons     = typeEnvTyCons env_tc
281     local_classes    = typeEnvClasses env_tc
282     imported_modules = map mod_name_to_Module imported_module_names
283     (fe_binders,h_code,c_code) = foreign_stuff
284
285     mod_name_to_Module :: ModuleName -> Module
286     mod_name_to_Module nm
287        = let str_mi = case lookupModuleEnvByName hit nm of
288                           Just mi -> mi
289                           Nothing -> case lookupModuleEnvByName pit nm of
290                                         Just mi -> mi
291                                         Nothing -> barf nm
292          in  mi_module str_mi
293     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
294                        (ppr nm)
295
296
297 dsThenSimplThenTidy dflags rule_base this_mod tc_result hst
298  = do --------------------------  Desugaring ----------------
299       -- _scc_     "DeSugar"
300       show_pass dflags "DeSugar"
301       ds_uniqs <- mkSplitUniqSupply 'd'
302       (desugared, rules, h_code, c_code, fe_binders) 
303          <- deSugar dflags this_mod ds_uniqs hst tc_result
304
305       --------------------------  Main Core-language transformations ----------------
306       -- _scc_     "Core2Core"
307       show_pass dflags "Core2Core"
308       (simplified, orphan_rules) 
309          <- core2core dflags rule_base hst desugared rules
310
311       -- Do the final tidy-up
312       show_pass dflags "CoreTidy"
313       (tidy_binds, tidy_orphan_rules) 
314          <- tidyCorePgm dflags this_mod simplified orphan_rules
315       
316       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
317
318
319 myCoreToStg dflags this_mod tidy_binds
320  = do 
321       c2s_uniqs <- mkSplitUniqSupply 'c'
322       st_uniqs  <- mkSplitUniqSupply 'g'
323       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
324
325       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
326       -- TEMP: the above call zaps some space usage allocated by the
327       -- simplifier, which for reasons I don't understand, persists
328       -- thoroughout code generation
329
330       show_pass dflags "Core2Stg"
331       -- _scc_     "Core2Stg"
332       let stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
333
334       show_pass dflags "Stg2Stg"
335       -- _scc_     "Stg2Stg"
336       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
337       let final_ids = collectFinalStgBinders (map fst stg_binds2)
338
339       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
340
341
342 show_pass dflags what
343   = if   dopt Opt_D_show_passes dflags
344     then hPutStr stderr ("*** "++what++":\n")
345     else return ()
346 \end{code}
347
348
349 %************************************************************************
350 %*                                                                      *
351 \subsection{Initial persistent state}
352 %*                                                                      *
353 %************************************************************************
354
355 \begin{code}
356 initPersistentCompilerState :: IO PersistentCompilerState
357 initPersistentCompilerState 
358   = do prs <- initPersistentRenamerState
359        return (
360         PCS { pcs_PIT   = emptyIfaceTable,
361               pcs_PTE   = wiredInThingEnv,
362               pcs_insts = emptyInstEnv,
363               pcs_rules = emptyRuleBase,
364               pcs_PRS   = prs
365             }
366         )
367
368 initPersistentRenamerState :: IO PersistentRenamerState
369   = do ns <- mkSplitUniqSupply 'r'
370        return (
371         PRS { prsOrig  = Orig { origNames  = initOrigNames,
372                                 origIParam = emptyFM },
373               prsDecls = emptyNameEnv,
374               prsInsts = emptyBag,
375               prsRules = emptyBag,
376               prsNS    = ns
377             }
378         )
379
380 initOrigNames :: FiniteMap (ModuleName,OccName) Name
381 initOrigNames 
382    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
383      where
384         grab names = foldl add emptyFM names
385         add env name 
386            = addToFM env (moduleName (nameModule name), nameOccName name) name
387
388
389 initRules :: PackageRuleBase
390 initRules = emptyRuleBase
391 {- SHOULD BE (ish)
392             foldl add emptyVarEnv builtinRules
393           where
394             add env (name,rule) 
395               = extendRuleBase env name rule
396 -}
397 \end{code}