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