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