[project @ 2000-11-07 16:03:38 by simonmar]
[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 Interpreter
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 FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
57 import OccName          ( OccName )
58 import Name             ( Name, nameModule, nameOccName, getName  )
59 import Name             ( emptyNameEnv )
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 (unJust (ml_hi_file location) "hscMain")
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       what_next dflags location maybe_checked_iface
109                 hst hit pcs_ch
110       }}
111
112
113 hscNoRecomp dflags location maybe_checked_iface hst hit pcs_ch
114  = do {
115       hPutStrLn stderr "COMPILATION NOT REQUIRED";
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       hPutStrLn stderr "COMPILATION IS REQUIRED";
155
156       -- what target are we shooting for?
157       let toInterp = dopt_HscLang dflags == HscInterpreted
158       ;
159       -- PARSE
160       maybe_parsed 
161          <- myParseModule dflags (unJust (ml_hspp_file location) "hscRecomp:hspp");
162       case maybe_parsed of {
163          Nothing -> return (HscFail pcs_ch);
164          Just rdr_module -> do {
165
166       -- RENAME
167       let this_mod = mkModuleInThisPackage (hsModuleName rdr_module)
168       ;
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 the final interface
203       final_iface 
204          <- mkFinalIface dflags location maybe_checked_iface new_iface new_details
205       ;
206       -- do the rest of code generation/emission
207       (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
208          <- restOfCodeGeneration dflags toInterp this_mod
209                (map ideclName (hsModuleImports rdr_module))
210                cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
211                hit (pcs_PIT pcs_tc)       
212       ;
213       -- and the answer is ...
214       return (HscOK new_details (Just final_iface)
215                     maybe_stub_h_filename maybe_stub_c_filename
216                     maybe_ibinds pcs_tc)
217       }}}}}}}
218
219
220
221 mkFinalIface dflags location maybe_old_iface new_iface new_details
222  = case completeIface maybe_old_iface new_iface new_details of
223       (new_iface, Nothing) -- no change in the interfacfe
224          -> do if dopt Opt_D_dump_hi_diffs dflags  then
225                         printDump (text "INTERFACE UNCHANGED")
226                   else  return ()
227                return new_iface
228       (new_iface, Just sdoc)
229          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "NEW INTERFACE" sdoc
230                -- Write the interface file
231                writeIface (unJust (ml_hi_file location) "hscRecomp:hi") new_iface
232                return new_iface
233
234
235 myParseModule dflags src_filename
236  = do --------------------------  Parser  ----------------
237       show_pass dflags "Parser"
238       -- _scc_     "Parser"
239
240       buf <- hGetStringBuffer True{-expand tabs-} src_filename
241
242       let glaexts | dopt Opt_GlasgowExts dflags = 1#
243                   | otherwise                 = 0#
244
245       case parse buf PState{ bol = 0#, atbol = 1#,
246                              context = [], glasgow_exts = glaexts,
247                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
248
249         PFailed err -> do { hPutStrLn stderr (showSDoc err);
250                             return Nothing };
251         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
252
253       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
254       
255       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
256                            (ppSourceStats False rdr_module) ;
257       
258       return (Just rdr_module)
259       }}
260
261
262 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info 
263                      foreign_stuff env_tc stg_binds oa_tidy_binds
264                      hit pit -- these last two for mapping ModNames to Modules
265  | toInterp
266  = do (ibinds,itbl_env) 
267          <- stgToInterpSyn (map fst stg_binds) local_tycons local_classes
268       return (Nothing, Nothing, Just (ibinds,itbl_env))
269
270  | otherwise
271  = do --------------------------  Code generation -------------------------------
272       show_pass dflags "CodeGen"
273       -- _scc_     "CodeGen"
274       abstractC <- codeGen dflags this_mod imported_modules
275                            cost_centre_info fe_binders
276                            local_tycons stg_binds
277
278       --------------------------  Code output -------------------------------
279       show_pass dflags "CodeOutput"
280       -- _scc_     "CodeOutput"
281       (maybe_stub_h_name, maybe_stub_c_name)
282          <- codeOutput dflags this_mod local_tycons
283                        oa_tidy_binds stg_binds
284                        c_code h_code abstractC
285
286       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
287  where
288     local_tycons     = typeEnvTyCons env_tc
289     local_classes    = typeEnvClasses env_tc
290     imported_modules = map mod_name_to_Module imported_module_names
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_PTE   = wiredInThingEnv,
370               pcs_insts = emptyInstEnv,
371               pcs_rules = emptyRuleBase,
372               pcs_PRS   = prs
373             }
374         )
375
376 initPersistentRenamerState :: IO PersistentRenamerState
377   = do ns <- mkSplitUniqSupply 'r'
378        return (
379         PRS { prsOrig  = Orig { origNames  = initOrigNames,
380                                 origIParam = emptyFM },
381               prsDecls = (emptyNameEnv, 0),
382               prsInsts = (emptyBag, 0),
383               prsRules = (emptyBag, 0),
384               prsNS    = ns
385             }
386         )
387
388 initOrigNames :: FiniteMap (ModuleName,OccName) Name
389 initOrigNames 
390    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
391      where
392         grab names = foldl add emptyFM names
393         add env name 
394            = addToFM env (moduleName (nameModule name), nameOccName name) name
395
396
397 initRules :: PackageRuleBase
398 initRules = emptyRuleBase
399 {- SHOULD BE (ish)
400             foldl add emptyVarEnv builtinRules
401           where
402             add env (name,rule) 
403               = extendRuleBase env name rule
404 -}
405 \end{code}