[project @ 2000-11-13 12:43:20 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               ( 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 for hs = " ++ show (ml_hs_file location)
96                 ++ ", hspp = " ++ show (ml_hspp_file location));
97
98       (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
99          <- checkOldIface dflags hit hst pcs (unJust (ml_hi_file location) "hscMain")
100                           source_unchanged maybe_old_iface;
101
102       if errs_found 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       what_next dflags location maybe_checked_iface
111                 hst hit pcs_ch
112       }}
113
114
115 hscNoRecomp dflags location maybe_checked_iface hst hit pcs_ch
116  = do {
117       hPutStrLn stderr "COMPILATION NOT REQUIRED";
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 <- typecheckModule dflags this_mod pcs_cl hst 
133                                          old_iface alwaysQualify 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         ; hPutStrLn stderr "COMPILATION IS REQUIRED";
157
158           -- what target are we shooting for?
159         ; let toInterp = dopt_HscLang dflags == HscInterpreted
160
161             -------------------
162             -- PARSE
163             -------------------
164         ; maybe_parsed <- myParseModule dflags (unJust (ml_hspp_file location) "hscRecomp:hspp")
165         ; case maybe_parsed of {
166              Nothing -> return (HscFail pcs_ch);
167              Just rdr_module -> do {
168         ; let this_mod = mkModuleInThisPackage (hsModuleName rdr_module)
169     
170             -------------------
171             -- RENAME
172             -------------------
173         ; (pcs_rn, maybe_rn_result) 
174              <- renameModule dflags hit hst pcs_ch this_mod rdr_module
175         ; case maybe_rn_result of {
176              Nothing -> return (HscFail pcs_rn);
177              Just (print_unqualified, new_iface, rn_hs_decls) -> do {
178     
179             -------------------
180             -- TYPECHECK
181             -------------------
182         ; maybe_tc_result <- typecheckModule dflags this_mod pcs_rn hst new_iface 
183                                              print_unqualified rn_hs_decls
184         ; case maybe_tc_result of {
185              Nothing -> do { hPutStrLn stderr "Typechecked failed" 
186                            ; return (HscFail pcs_rn) } ;
187              Just tc_result -> do {
188     
189         ; let pcs_tc        = tc_pcs tc_result
190               env_tc        = tc_env tc_result
191               local_insts   = tc_insts tc_result
192
193             -------------------
194             -- DESUGAR, SIMPLIFY, TIDY-CORE
195             -------------------
196           -- We grab the the unfoldings at this point.
197         ; simpl_result <- dsThenSimplThenTidy dflags (pcs_rules pcs_tc) this_mod 
198                                               print_unqualified tc_result hst
199         ; let (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
200             
201             -------------------
202             -- CONVERT TO STG
203             -------------------
204         ; (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids) 
205              <- myCoreToStg dflags this_mod tidy_binds
206
207
208             -------------------
209             -- BUILD THE NEW ModDetails AND ModIface
210             -------------------
211         ; let new_details = mkModDetails env_tc local_insts tidy_binds 
212                                          top_level_ids orphan_rules
213         ; final_iface <- mkFinalIface dflags location maybe_checked_iface 
214                                       new_iface new_details
215
216             -------------------
217             -- COMPLETE CODE GENERATION
218             -------------------
219         ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
220              <- restOfCodeGeneration dflags toInterp this_mod
221                    (map ideclName (hsModuleImports rdr_module))
222                    cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
223                    hit (pcs_PIT pcs_tc)       
224
225           -- and the answer is ...
226         ; return (HscOK new_details (Just final_iface)
227                         maybe_stub_h_filename maybe_stub_c_filename
228                         maybe_ibinds pcs_tc)
229           }}}}}}}
230
231
232
233 mkFinalIface dflags location maybe_old_iface new_iface new_details
234  = case completeIface maybe_old_iface new_iface new_details of
235       (new_iface, Nothing) -- no change in the interfacfe
236          -> do if dopt Opt_D_dump_hi_diffs dflags  then
237                         printDump (text "INTERFACE UNCHANGED")
238                   else  return ()
239                return new_iface
240       (new_iface, Just sdoc)
241          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "NEW INTERFACE" sdoc
242                -- Write the interface file
243                writeIface (unJust (ml_hi_file location) "hscRecomp:hi") new_iface
244                return new_iface
245
246
247 myParseModule dflags src_filename
248  = do --------------------------  Parser  ----------------
249       showPass dflags "Parser"
250       -- _scc_     "Parser"
251
252       buf <- hGetStringBuffer True{-expand tabs-} src_filename
253
254       let glaexts | dopt Opt_GlasgowExts dflags = 1#
255                   | otherwise                 = 0#
256
257       case parse buf PState{ bol = 0#, atbol = 1#,
258                              context = [], glasgow_exts = glaexts,
259                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
260
261         PFailed err -> do { hPutStrLn stderr (showSDoc err);
262                             return Nothing };
263         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
264
265       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
266       
267       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
268                            (ppSourceStats False rdr_module) ;
269       
270       return (Just rdr_module)
271       }}
272
273
274 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info 
275                      foreign_stuff env_tc stg_binds oa_tidy_binds
276                      hit pit -- these last two for mapping ModNames to Modules
277  | toInterp
278  = do (ibinds,itbl_env) 
279          <- stgToInterpSyn (map fst stg_binds) local_tycons local_classes
280       return (Nothing, Nothing, Just (ibinds,itbl_env))
281
282  | otherwise
283  = do --------------------------  Code generation -------------------------------
284       -- _scc_     "CodeGen"
285       abstractC <- codeGen dflags this_mod imported_modules
286                            cost_centre_info fe_binders
287                            local_tycons stg_binds
288
289       --------------------------  Code output -------------------------------
290       -- _scc_     "CodeOutput"
291       (maybe_stub_h_name, maybe_stub_c_name)
292          <- codeOutput dflags this_mod local_tycons
293                        oa_tidy_binds stg_binds
294                        c_code h_code abstractC
295
296       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
297  where
298     local_tycons     = typeEnvTyCons env_tc
299     local_classes    = typeEnvClasses env_tc
300     imported_modules = map mod_name_to_Module imported_module_names
301     (fe_binders,h_code,c_code) = foreign_stuff
302
303     mod_name_to_Module :: ModuleName -> Module
304     mod_name_to_Module nm
305        = let str_mi = case lookupModuleEnvByName hit nm of
306                           Just mi -> mi
307                           Nothing -> case lookupModuleEnvByName pit nm of
308                                         Just mi -> mi
309                                         Nothing -> barf nm
310          in  mi_module str_mi
311     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
312                        (ppr nm)
313
314
315 dsThenSimplThenTidy dflags rule_base this_mod print_unqual tc_result hst
316  = do --------------------------  Desugaring ----------------
317       -- _scc_     "DeSugar"
318       (desugared, rules, h_code, c_code, fe_binders) 
319          <- deSugar dflags this_mod print_unqual hst tc_result
320
321       --------------------------  Main Core-language transformations ----------------
322       -- _scc_     "Core2Core"
323       (simplified, orphan_rules) 
324          <- core2core dflags rule_base hst desugared rules
325
326       -- Do the final tidy-up
327       (tidy_binds, tidy_orphan_rules) 
328          <- tidyCorePgm dflags this_mod simplified orphan_rules
329       
330       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
331
332
333 myCoreToStg dflags this_mod tidy_binds
334  = do 
335       c2s_uniqs <- mkSplitUniqSupply 'c'
336       st_uniqs  <- mkSplitUniqSupply 'g'
337       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
338
339       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
340       -- TEMP: the above call zaps some space usage allocated by the
341       -- simplifier, which for reasons I don't understand, persists
342       -- thoroughout code generation
343
344       showPass dflags "Core2Stg"
345       -- _scc_     "Core2Stg"
346       let stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
347
348       showPass dflags "Stg2Stg"
349       -- _scc_     "Stg2Stg"
350       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
351       let final_ids = collectFinalStgBinders (map fst stg_binds2)
352
353       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
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}