[project @ 2000-11-01 17:15:28 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 "CHECKING OLD IFACE";
99       (pcs_ch, check_errs, (recomp_reqd, maybe_checked_iface))
100          <- checkOldIface dflags hit hst pcs (unJust (ml_hi_file location) "hscMain")
101                           source_unchanged maybe_old_iface;
102       if check_errs 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
133          <- typecheckModule dflags this_mod pcs_cl hst hit 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       -- 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 the final interface
205       final_iface 
206          <- mkFinalIface dflags location maybe_checked_iface new_iface new_details
207       ;
208       -- do the rest of code generation/emission
209       (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
210          <- restOfCodeGeneration dflags toInterp this_mod
211                (map ideclName (hsModuleImports rdr_module))
212                cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
213                hit (pcs_PIT pcs_tc)       
214       ;
215       -- and the answer is ...
216       return (HscOK new_details (Just final_iface)
217                     maybe_stub_h_filename maybe_stub_c_filename
218                     maybe_ibinds pcs_tc)
219       }}}}}}}
220
221
222
223 mkFinalIface dflags location maybe_old_iface new_iface new_details
224  = case completeIface maybe_old_iface new_iface new_details of
225       (new_iface, Nothing) -- no change in the interfacfe
226          -> do if dopt Opt_D_dump_hi_diffs dflags  then
227                         printDump (text "INTERFACE UNCHANGED")
228                   else  return ()
229                return new_iface
230       (new_iface, Just sdoc)
231          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "NEW INTERFACE" sdoc
232                -- Write the interface file
233                writeIface (unJust (ml_hi_file location) "hscRecomp:hi") new_iface
234                return new_iface
235
236
237 myParseModule dflags src_filename
238  = do --------------------------  Parser  ----------------
239       show_pass dflags "Parser"
240       -- _scc_     "Parser"
241
242       buf <- hGetStringBuffer True{-expand tabs-} src_filename
243
244       let glaexts | dopt Opt_GlasgowExts dflags = 1#
245                   | otherwise                 = 0#
246
247       case parse buf PState{ bol = 0#, atbol = 1#,
248                              context = [], glasgow_exts = glaexts,
249                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
250
251         PFailed err -> do { hPutStrLn stderr (showSDoc err);
252                             return Nothing };
253         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
254
255       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
256       
257       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
258                            (ppSourceStats False rdr_module) ;
259       
260       return (Just rdr_module)
261       }}
262
263
264 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info 
265                      foreign_stuff env_tc stg_binds oa_tidy_binds
266                      hit pit -- these last two for mapping ModNames to Modules
267  | toInterp
268  = do (ibinds,itbl_env) 
269          <- stgToInterpSyn (map fst stg_binds) local_tycons local_classes
270       return (Nothing, Nothing, Just (ibinds,itbl_env))
271
272  | otherwise
273  = do --------------------------  Code generation -------------------------------
274       show_pass dflags "CodeGen"
275       -- _scc_     "CodeGen"
276       abstractC <- codeGen dflags this_mod imported_modules
277                            cost_centre_info fe_binders
278                            local_tycons stg_binds
279
280       --------------------------  Code output -------------------------------
281       show_pass dflags "CodeOutput"
282       -- _scc_     "CodeOutput"
283       (maybe_stub_h_name, maybe_stub_c_name)
284          <- codeOutput dflags this_mod local_tycons
285                        oa_tidy_binds stg_binds
286                        c_code h_code abstractC
287
288       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
289  where
290     local_tycons     = typeEnvTyCons env_tc
291     local_classes    = typeEnvClasses env_tc
292     imported_modules = map mod_name_to_Module imported_module_names
293     (fe_binders,h_code,c_code) = foreign_stuff
294
295     mod_name_to_Module :: ModuleName -> Module
296     mod_name_to_Module nm
297        = let str_mi = case lookupModuleEnvByName hit nm of
298                           Just mi -> mi
299                           Nothing -> case lookupModuleEnvByName pit nm of
300                                         Just mi -> mi
301                                         Nothing -> barf nm
302          in  mi_module str_mi
303     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
304                        (ppr nm)
305
306
307 dsThenSimplThenTidy dflags rule_base this_mod tc_result hst
308  = do --------------------------  Desugaring ----------------
309       -- _scc_     "DeSugar"
310       show_pass dflags "DeSugar"
311       ds_uniqs <- mkSplitUniqSupply 'd'
312       (desugared, rules, h_code, c_code, fe_binders) 
313          <- deSugar dflags this_mod ds_uniqs hst tc_result
314
315       --------------------------  Main Core-language transformations ----------------
316       -- _scc_     "Core2Core"
317       show_pass dflags "Core2Core"
318       (simplified, orphan_rules) 
319          <- core2core dflags rule_base hst desugared rules
320
321       -- Do the final tidy-up
322       show_pass dflags "CoreTidy"
323       (tidy_binds, tidy_orphan_rules) 
324          <- tidyCorePgm dflags this_mod simplified orphan_rules
325       
326       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
327
328
329 myCoreToStg dflags this_mod tidy_binds
330  = do 
331       c2s_uniqs <- mkSplitUniqSupply 'c'
332       st_uniqs  <- mkSplitUniqSupply 'g'
333       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
334
335       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
336       -- TEMP: the above call zaps some space usage allocated by the
337       -- simplifier, which for reasons I don't understand, persists
338       -- thoroughout code generation
339
340       show_pass dflags "Core2Stg"
341       -- _scc_     "Core2Stg"
342       let stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
343
344       show_pass dflags "Stg2Stg"
345       -- _scc_     "Stg2Stg"
346       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
347       let final_ids = collectFinalStgBinders (map fst stg_binds2)
348
349       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
350
351
352 show_pass dflags what
353   = if   dopt Opt_D_show_passes dflags
354     then hPutStr stderr ("*** "++what++":\n")
355     else return ()
356 \end{code}
357
358
359 %************************************************************************
360 %*                                                                      *
361 \subsection{Initial persistent state}
362 %*                                                                      *
363 %************************************************************************
364
365 \begin{code}
366 initPersistentCompilerState :: IO PersistentCompilerState
367 initPersistentCompilerState 
368   = do prs <- initPersistentRenamerState
369        return (
370         PCS { pcs_PIT   = emptyIfaceTable,
371               pcs_PTE   = wiredInThingEnv,
372               pcs_insts = emptyInstEnv,
373               pcs_rules = emptyRuleBase,
374               pcs_PRS   = prs
375             }
376         )
377
378 initPersistentRenamerState :: IO PersistentRenamerState
379   = do ns <- mkSplitUniqSupply 'r'
380        return (
381         PRS { prsOrig  = Orig { origNames  = initOrigNames,
382                                 origIParam = emptyFM },
383               prsDecls = emptyNameEnv,
384               prsInsts = emptyBag,
385               prsRules = emptyBag,
386               prsNS    = ns
387             }
388         )
389
390 initOrigNames :: FiniteMap (ModuleName,OccName) Name
391 initOrigNames 
392    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
393      where
394         grab names = foldl add emptyFM names
395         add env name 
396            = addToFM env (moduleName (nameModule name), nameOccName name) name
397
398
399 initRules :: PackageRuleBase
400 initRules = emptyRuleBase
401 {- SHOULD BE (ish)
402             foldl add emptyVarEnv builtinRules
403           where
404             add env (name,rule) 
405               = extendRuleBase env name rule
406 -}
407 \end{code}