[project @ 2000-11-10 15:12:50 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               ( 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 MkIface          ( completeIface, mkModDetailsFromIface, mkModDetails,
26                           writeIface )
27 import TcModule         ( TcResults(..), typecheckModule )
28 import InstEnv          ( emptyInstEnv )
29 import Desugar          ( deSugar )
30 import SimplCore        ( core2core )
31 import OccurAnal        ( occurAnalyseBinds )
32 import CoreUtils        ( coreBindsSize )
33 import CoreTidy         ( tidyCorePgm )
34 import CoreToStg        ( topCoreBindsToStg )
35 import StgSyn           ( collectFinalStgBinders )
36 import SimplStg         ( stg2stg )
37 import CodeGen          ( codeGen )
38 import CodeOutput       ( codeOutput )
39
40 import Module           ( ModuleName, moduleName, mkModuleInThisPackage )
41 import CmdLineOpts
42 import ErrUtils         ( dumpIfSet_dyn, showPass )
43 import Util             ( unJust )
44 import UniqSupply       ( mkSplitUniqSupply )
45
46 import Bag              ( emptyBag )
47 import Outputable
48 import Interpreter      ( UnlinkedIBind, ItblEnv, 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 FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
56 import OccName          ( OccName )
57 import Name             ( Name, nameModule, nameOccName, getName  )
58 import Name             ( emptyNameEnv )
59 import Module           ( Module, lookupModuleEnvByName )
60
61 \end{code}
62
63
64 %************************************************************************
65 %*                                                                      *
66 \subsection{The main compiler pipeline}
67 %*                                                                      *
68 %************************************************************************
69
70 \begin{code}
71 data HscResult
72    = HscOK   ModDetails              -- new details (HomeSymbolTable additions)
73              (Maybe ModIface)        -- new iface (if any compilation was done)
74              (Maybe String)          -- generated stub_h filename (in /tmp)
75              (Maybe String)          -- generated stub_c filename (in /tmp)
76              (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
77              PersistentCompilerState -- updated PCS
78
79    | HscFail PersistentCompilerState -- updated PCS
80         -- no errors or warnings; the individual passes
81         -- (parse/rename/typecheck) print messages themselves
82
83 hscMain
84   :: DynFlags
85   -> Bool                       -- source unchanged?
86   -> ModuleLocation             -- location info
87   -> Maybe ModIface             -- old interface, if available
88   -> HomeSymbolTable            -- for home module ModDetails
89   -> HomeIfaceTable
90   -> PersistentCompilerState    -- IN: persistent compiler state
91   -> IO HscResult
92
93 hscMain dflags source_unchanged location maybe_old_iface hst hit pcs
94  = do {
95       putStrLn "CHECKING OLD IFACE";
96       (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
97          <- checkOldIface dflags hit hst pcs (unJust (ml_hi_file location) "hscMain")
98                           source_unchanged maybe_old_iface;
99
100       if errs_found 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 <- typecheckModule dflags this_mod pcs_cl hst 
131                                          old_iface alwaysQualify 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             -------------------
160             -- PARSE
161             -------------------
162         ; maybe_parsed <- 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         ; let this_mod = mkModuleInThisPackage (hsModuleName rdr_module)
167     
168             -------------------
169             -- RENAME
170             -------------------
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 (print_unqualified, new_iface, rn_hs_decls) -> do {
176     
177             -------------------
178             -- TYPECHECK
179             -------------------
180         ; maybe_tc_result <- typecheckModule dflags this_mod pcs_rn hst new_iface 
181                                              print_unqualified 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             -------------------
192             -- DESUGAR, SIMPLIFY, TIDY-CORE
193             -------------------
194           -- We grab the the unfoldings at this point.
195         ; simpl_result <- dsThenSimplThenTidy dflags (pcs_rules pcs_tc) this_mod 
196                                               print_unqualified tc_result hst
197         ; let (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
198             
199             -------------------
200             -- CONVERT TO STG
201             -------------------
202         ; (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids) 
203              <- myCoreToStg dflags this_mod tidy_binds
204
205
206             -------------------
207             -- BUILD THE NEW ModDetails AND ModIface
208             -------------------
209         ; let new_details = mkModDetails env_tc local_insts tidy_binds 
210                                          top_level_ids orphan_rules
211         ; final_iface <- mkFinalIface dflags location maybe_checked_iface 
212                                       new_iface new_details
213
214             -------------------
215             -- COMPLETE CODE GENERATION
216             -------------------
217         ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
218              <- restOfCodeGeneration dflags toInterp this_mod
219                    (map ideclName (hsModuleImports rdr_module))
220                    cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
221                    hit (pcs_PIT pcs_tc)       
222
223           -- and the answer is ...
224         ; return (HscOK new_details (Just final_iface)
225                         maybe_stub_h_filename maybe_stub_c_filename
226                         maybe_ibinds pcs_tc)
227           }}}}}}}
228
229
230
231 mkFinalIface dflags location maybe_old_iface new_iface new_details
232  = case completeIface maybe_old_iface new_iface new_details of
233       (new_iface, Nothing) -- no change in the interfacfe
234          -> do if dopt Opt_D_dump_hi_diffs dflags  then
235                         printDump (text "INTERFACE UNCHANGED")
236                   else  return ()
237                return new_iface
238       (new_iface, Just sdoc)
239          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "NEW INTERFACE" sdoc
240                -- Write the interface file
241                writeIface (unJust (ml_hi_file location) "hscRecomp:hi") new_iface
242                return new_iface
243
244
245 myParseModule dflags src_filename
246  = do --------------------------  Parser  ----------------
247       showPass dflags "Parser"
248       -- _scc_     "Parser"
249
250       buf <- hGetStringBuffer True{-expand tabs-} src_filename
251
252       let glaexts | dopt Opt_GlasgowExts dflags = 1#
253                   | otherwise                 = 0#
254
255       case parse buf PState{ bol = 0#, atbol = 1#,
256                              context = [], glasgow_exts = glaexts,
257                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
258
259         PFailed err -> do { hPutStrLn stderr (showSDoc err);
260                             return Nothing };
261         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
262
263       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
264       
265       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
266                            (ppSourceStats False rdr_module) ;
267       
268       return (Just rdr_module)
269       }}
270
271
272 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info 
273                      foreign_stuff env_tc stg_binds oa_tidy_binds
274                      hit pit -- these last two for mapping ModNames to Modules
275  | toInterp
276  = do (ibinds,itbl_env) 
277          <- stgToInterpSyn (map fst stg_binds) local_tycons local_classes
278       return (Nothing, Nothing, Just (ibinds,itbl_env))
279
280  | otherwise
281  = do --------------------------  Code generation -------------------------------
282       -- _scc_     "CodeGen"
283       abstractC <- codeGen dflags this_mod imported_modules
284                            cost_centre_info fe_binders
285                            local_tycons stg_binds
286
287       --------------------------  Code output -------------------------------
288       -- _scc_     "CodeOutput"
289       (maybe_stub_h_name, maybe_stub_c_name)
290          <- codeOutput dflags this_mod local_tycons
291                        oa_tidy_binds stg_binds
292                        c_code h_code abstractC
293
294       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
295  where
296     local_tycons     = typeEnvTyCons env_tc
297     local_classes    = typeEnvClasses env_tc
298     imported_modules = map mod_name_to_Module imported_module_names
299     (fe_binders,h_code,c_code) = foreign_stuff
300
301     mod_name_to_Module :: ModuleName -> Module
302     mod_name_to_Module nm
303        = let str_mi = case lookupModuleEnvByName hit nm of
304                           Just mi -> mi
305                           Nothing -> case lookupModuleEnvByName pit nm of
306                                         Just mi -> mi
307                                         Nothing -> barf nm
308          in  mi_module str_mi
309     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
310                        (ppr nm)
311
312
313 dsThenSimplThenTidy dflags rule_base this_mod print_unqual tc_result hst
314  = do --------------------------  Desugaring ----------------
315       -- _scc_     "DeSugar"
316       (desugared, rules, h_code, c_code, fe_binders) 
317          <- deSugar dflags this_mod print_unqual hst tc_result
318
319       --------------------------  Main Core-language transformations ----------------
320       -- _scc_     "Core2Core"
321       (simplified, orphan_rules) 
322          <- core2core dflags rule_base hst desugared rules
323
324       -- Do the final tidy-up
325       (tidy_binds, tidy_orphan_rules) 
326          <- tidyCorePgm dflags this_mod simplified orphan_rules
327       
328       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
329
330
331 myCoreToStg dflags this_mod tidy_binds
332  = do 
333       c2s_uniqs <- mkSplitUniqSupply 'c'
334       st_uniqs  <- mkSplitUniqSupply 'g'
335       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
336
337       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
338       -- TEMP: the above call zaps some space usage allocated by the
339       -- simplifier, which for reasons I don't understand, persists
340       -- thoroughout code generation
341
342       showPass dflags "Core2Stg"
343       -- _scc_     "Core2Stg"
344       let stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
345
346       showPass dflags "Stg2Stg"
347       -- _scc_     "Stg2Stg"
348       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
349       let final_ids = collectFinalStgBinders (map fst stg_binds2)
350
351       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
352 \end{code}
353
354
355 %************************************************************************
356 %*                                                                      *
357 \subsection{Initial persistent state}
358 %*                                                                      *
359 %************************************************************************
360
361 \begin{code}
362 initPersistentCompilerState :: IO PersistentCompilerState
363 initPersistentCompilerState 
364   = do prs <- initPersistentRenamerState
365        return (
366         PCS { pcs_PIT   = emptyIfaceTable,
367               pcs_PTE   = wiredInThingEnv,
368               pcs_insts = emptyInstEnv,
369               pcs_rules = emptyRuleBase,
370               pcs_PRS   = prs
371             }
372         )
373
374 initPersistentRenamerState :: IO PersistentRenamerState
375   = do ns <- mkSplitUniqSupply 'r'
376        return (
377         PRS { prsOrig  = Orig { origNames  = initOrigNames,
378                                 origIParam = emptyFM },
379               prsDecls = (emptyNameEnv, 0),
380               prsInsts = (emptyBag, 0),
381               prsRules = (emptyBag, 0),
382               prsNS    = ns
383             }
384         )
385
386 initOrigNames :: FiniteMap (ModuleName,OccName) Name
387 initOrigNames 
388    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
389      where
390         grab names = foldl add emptyFM names
391         add env name 
392            = addToFM env (moduleName (nameModule name), nameOccName name) name
393
394
395 initRules :: PackageRuleBase
396 initRules = emptyRuleBase
397 {- SHOULD BE (ish)
398             foldl add emptyVarEnv builtinRules
399           where
400             add env (name,rule) 
401               = extendRuleBase env name rule
402 -}
403 \end{code}