2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
4 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
7 module HscMain ( hscMain ) where
9 #include "HsVersions.h"
11 import IO ( hPutStr, stderr )
14 import RdrHsSyn ( RdrNameHsModule )
15 import FastString ( unpackFS )
16 import StringBuffer ( hGetStringBuffer )
17 import Parser ( parse )
18 import Lex ( PState(..), ParseResult(..) )
19 import SrcLoc ( mkSrcLoc )
21 import Rename ( renameModule )
23 import PrelInfo ( wiredInThings )
24 import PrelRules ( builtinRules )
25 import MkIface ( writeIface )
26 import TcModule ( TcResults(..), typecheckModule )
27 import Desugar ( deSugar )
28 import SimplCore ( core2core )
29 import OccurAnal ( occurAnalyseBinds )
30 import CoreUtils ( coreBindsSize )
31 import CoreTidy ( tidyCorePgm )
32 import CoreToStg ( topCoreBindsToStg )
33 import StgSyn ( collectFinalStgBinders )
34 import SimplStg ( stg2stg )
35 import CodeGen ( codeGen )
36 import CodeOutput ( codeOutput )
38 import Module ( ModuleName, moduleNameUserString )
40 import ErrUtils ( ghcExit, doIfSet, dumpIfSet )
41 import UniqSupply ( mkSplitUniqSupply )
44 import Char ( isSpace )
45 import StgInterp ( runStgI )
46 import HscStats ( ppSourceStats )
50 %************************************************************************
52 \subsection{The main compiler pipeline}
54 %************************************************************************
58 = HscOK ModDetails -- new details (HomeSymbolTable additions)
59 (Maybe ModIface) -- new iface (if any compilation was done)
60 (Maybe String) -- generated stub_h filename (in /tmp)
61 (Maybe String) -- generated stub_c filename (in /tmp)
62 (Maybe [UnlinkedIBind]) -- interpreted code, if any
63 PersistentCompilerState -- updated PCS
65 | HscFail PersistentCompilerState -- updated PCS
66 -- no errors or warnings; the individual passes
67 -- (parse/rename/typecheck) print messages themselves
71 -> ModSummary -- summary, including source filename
72 -> Maybe ModIFace -- old interface, if available
73 -> String -- file in which to put the output (.s, .hc, .java etc.)
74 -> HomeSymbolTable -- for home module ModDetails
75 -> PersistentCompilerState -- IN: persistent compiler state
78 hscMain dflags core_cmds stg_cmds summary maybe_old_iface
79 output_filename mod_details pcs1
81 source_unchanged :: Bool -- extracted from summary?
83 (pcs2, check_errs, (recomp_reqd, maybe_checked_iface))
84 <- checkOldIface dflags finder hit hst pcs1 mod source_unchanged
87 -- test check_errs and give up if a problem happened
88 what_next = if recomp_reqd then hscRecomp else hscNoRecomp
91 what_next dflags core_cmds stg_cmds summary hit hst
92 pcs2 maybe_checked_iface
94 hscNoRecomp = panic "hscNoRecomp"
96 hscRecomp dflags core_cmds stg_cmds summary hit hst pcs maybe_old_iface
98 -- what target are we shooting for?
99 let toInterp = dopt_HscLang dflags == HscInterpreted;
102 maybe_parsed <- myParseModule dflags summary;
103 case maybe_parsed of {
104 Nothing -> return (HscFail pcs);
105 Just rdr_module -> do {
108 (pcs_rn, maybe_rn_result)
109 <- renameModule dflags finder hit hst pcs mod rdr_module;
110 case maybe_rn_result of {
111 Nothing -> return (HscFail pcs_rn);
112 Just (new_iface, rn_hs_decls) -> do {
116 <- typecheckModule dflags mod pcs_rn hst hit pit rn_hs_decls;
117 case maybe_tc_result of {
118 Nothing -> return (HscFail pcs_rn);
119 Just tc_result -> do {
121 let pcs_tc = tc_pcs tc_result
122 let env_tc = tc_env tc_result
123 let binds_tc = tc_binds tc_result
124 let local_tycons = tc_tycons tc_result
125 let local_classes = tc_classes tc_result
127 -- DESUGAR, SIMPLIFY, TIDY-CORE
128 -- We grab the the unfoldings at this point.
129 (tidy_binds, orphan_rules, fe_binders, h_code, c_code) -- return modDetails?
130 <- dsThenSimplThenTidy dflags mod tc_result rule_base ds_uniqs
133 (stg_binds, cost_centre_info, top_level_ids)
134 <- myCoreToStg c2s_uniqs st_uniqs this_mod tidy_binds
136 -- cook up a new ModDetails now we (finally) have all the bits
137 let new_details = completeModDetails tc_env tidy_binds top_level_ids orphan_rules
139 -- and possibly create a new ModIface
140 let maybe_final_iface = completeIface maybe_old_iface new_iface new_details
142 -- do the rest of code generation/emission
143 (maybe_ibinds, maybe_stub_h_filename, maybe_stub_c_filename)
144 <- restOfCodeGeneration toInterp
145 this_mod imported_modules cost_centre_info
146 fe_binders local_tycons local_classes stg_binds
148 -- and the answer is ...
149 return (HscOK new_details maybe_final_iface
150 maybe_stub_h_filename maybe_stub_c_filename
154 myParseModule dflags summary
155 = do -------------------------- Reader ----------------
159 let src_filename -- name of the preprocessed source file
160 = case ms_ppsource summary of
161 Just (filename, fingerprint) -> filename
162 Nothing -> pprPanic "myParseModule:summary is not of a source module"
165 buf <- hGetStringBuffer True{-expand tabs-} src_filename
167 let glaexts | dopt Opt_GlasgowExts dflags = 1#
170 case parse buf PState{ bol = 0#, atbol = 1#,
171 context = [], glasgow_exts = glaexts,
172 loc = mkSrcLoc src_filename 1 } of {
174 PFailed err -> do hPutStrLn stderr (showSDoc err)
176 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) ->
178 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module)
179 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
180 (ppSourceStats False rdr_module)
182 return (Just rdr_module)
185 restOfCodeGeneration toInterp this_mod imported_modules cost_centre_info
186 fe_binders local_tycons local_classes stg_binds
188 = return (Nothing, Nothing, stgToIBinds stg_binds local_tycons local_classes)
191 = do -------------------------- Code generation -------------------------------
194 abstractC <- codeGen this_mod imported_modules
195 cost_centre_info fe_binders
196 local_tycons local_classes stg_binds
198 -------------------------- Code output -------------------------------
199 show_pass "CodeOutput"
200 -- _scc_ "CodeOutput"
201 (maybe_stub_h_name, maybe_stub_c_name)
202 <- codeOutput this_mod local_tycons local_classes
203 occ_anal_tidy_binds stg_binds2
204 c_code h_code abstractC ncg_uniqs
206 return (maybe_stub_h_name, maybe_stub_c_name, [{-UnlinkedIBind-}])
209 dsThenSimplThenTidy dflags mod tc_result rule_base ds_uniqs
210 = do -------------------------- Desugaring ----------------
212 (desugared, rules, h_code, c_code, fe_binders)
213 <- deSugar this_mod ds_uniqs tc_results
215 -------------------------- Main Core-language transformations ----------------
217 (simplified, orphan_rules) <- core2core core_cmds desugared rules
219 -- Do the final tidy-up
220 (tidy_binds, tidy_orphan_rules)
221 <- tidyCorePgm this_mod simplified orphan_rules
223 return (tidy_binds, tidy_orphan_rules, fe_binders, h_code, c_code)
227 myCoreToStg c2s_uniqs st_uniqs this_mod tidy_binds
228 = do let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
230 () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
231 -- TEMP: the above call zaps some space usage allocated by the
232 -- simplifier, which for reasons I don't understand, persists
233 -- thoroughout code generation
237 let stg_binds = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
241 (stg_binds2, cost_centre_info) <- stg2stg stg_cmds this_mod st_uniqs stg_binds
242 let final_ids = collectFinalStgBinders (map fst stg_binds2)
244 return (stg_binds2, cost_centre_info, final_ids)
248 -------------------------- Reader ----------------
249 show_pass "Parser" >>
252 let src_filename -- name of the preprocessed source file
253 = case ms_ppsource summary of
254 Just (filename, fingerprint) -> filename
255 Nothing -> pprPanic "hscMain:summary is not of a source module"
258 buf <- hGetStringBuffer True{-expand tabs-} src_filename
260 let glaexts | dopt Opt_GlasgowExts dflags = 1#
263 case parse buf PState{ bol = 0#, atbol = 1#,
264 context = [], glasgow_exts = glaexts,
265 loc = mkSrcLoc src_filename 1 } of {
267 PFailed err -> return (HscErrs pcs (unitBag err) emptyBag)
269 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) ->
271 dumpIfSet (dopt_D_dump_parsed flags) "Parser" (ppr rdr_module) >>
273 dumpIfSet (dopt_D_source_stats flags) "Source Statistics"
274 (ppSourceStats False rdr_module) >>
276 -- UniqueSupplies for later use (these are the only lower case uniques)
277 mkSplitUniqSupply 'd' >>= \ ds_uniqs -> -- desugarer
278 mkSplitUniqSupply 'r' >>= \ ru_uniqs -> -- rules
279 mkSplitUniqSupply 'c' >>= \ c2s_uniqs -> -- core-to-stg
280 mkSplitUniqSupply 'g' >>= \ st_uniqs -> -- stg-to-stg passes
281 mkSplitUniqSupply 'n' >>= \ ncg_uniqs -> -- native-code generator
283 -------------------------- Rename ----------------
284 show_pass "Renamer" >>
287 renameModule dflags finder pcs hst rdr_module
288 >>= \ (pcs_rn, maybe_rn_stuff) ->
289 case maybe_rn_stuff of {
290 Nothing -> -- Hurrah! Renamer reckons that there's no need to
292 reportCompile mod_name "Compilation NOT required!" >>
295 Just (this_mod, rn_mod,
296 old_iface, new_iface,
297 rn_name_supply, fixity_env,
299 -- Oh well, we've got to recompile for real
302 -------------------------- Typechecking ----------------
303 show_pass "TypeCheck" >>
305 typecheckModule dflags mod pcs hst hit pit rn_mod
306 -- tc_uniqs rn_name_supply
308 >>= \ maybe_tc_stuff ->
309 case maybe_tc_stuff of {
310 Nothing -> ghcExit 1; -- Type checker failed
312 Just (tc_results@(TcResults {tc_tycons = local_tycons,
313 tc_classes = local_classes,
314 tc_insts = inst_info })) ->
317 -------------------------- Desugaring ----------------
319 deSugar this_mod ds_uniqs tc_results >>= \ (desugared, rules, h_code, c_code, fe_binders) ->
322 -------------------------- Main Core-language transformations ----------------
324 core2core core_cmds desugared rules >>= \ (simplified, orphan_rules) ->
326 -- Do the final tidy-up
328 simplified orphan_rules >>= \ (tidy_binds, tidy_orphan_rules) ->
330 -- Run the occurrence analyser one last time, so that
331 -- dead binders get dead-binder info. This is exploited by
332 -- code generators to avoid spitting out redundant bindings.
333 -- The occurrence-zapping in Simplify.simplCaseBinder means
334 -- that the Simplifier nukes useful dead-var stuff especially
336 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds in
338 coreBindsSize occ_anal_tidy_binds `seq`
339 -- TEMP: the above call zaps some space usage allocated by the
340 -- simplifier, which for reasons I don't understand, persists
341 -- thoroughout code generation
345 -------------------------- Convert to STG code -------------------------------
346 show_pass "Core2Stg" >>
349 stg_binds = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
352 -------------------------- Simplify STG code -------------------------------
353 show_pass "Stg2Stg" >>
355 stg2stg stg_cmds this_mod st_uniqs stg_binds >>= \ (stg_binds2, cost_centre_info) ->
358 runStgI local_tycons local_classes
359 (map fst stg_binds2) >>= \ i_result ->
360 putStr ("\nANSWER = " ++ show i_result ++ "\n\n")
364 -------------------------- Interface file -------------------------------
365 -- Dump instance decls and type signatures into the interface file
368 final_ids = collectFinalStgBinders (map fst stg_binds2)
370 writeIface this_mod old_iface new_iface
371 local_tycons local_classes inst_info
372 final_ids occ_anal_tidy_binds tidy_orphan_rules >>
375 -------------------------- Code generation -------------------------------
376 show_pass "CodeGen" >>
378 codeGen this_mod imported_modules
381 local_tycons local_classes
382 stg_binds2 >>= \ abstractC ->
385 -------------------------- Code output -------------------------------
386 show_pass "CodeOutput" >>
388 codeOutput this_mod local_tycons local_classes
389 occ_anal_tidy_binds stg_binds2
390 c_code h_code abstractC
394 -------------------------- Final report -------------------------------
395 reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
403 -------------------------------------------------------------
404 -- ****** help functions:
407 = if opt_D_show_passes
408 then \ what -> hPutStr stderr ("*** "++what++":\n")
409 else \ what -> return ()
415 %************************************************************************
417 \subsection{Initial persistent state}
419 %************************************************************************
422 initPersistentCompilerState :: IO PersistentCompilerState
423 initPersistentCompilerState
425 = do prs <- initPersistentRenamerState
427 PCS { pcs_PST = initPackageDetails,
428 pcs_insts = emptyInstEnv,
429 pcs_rules = emptyRuleEnv,
430 pcs_PRS = initPersistentRenamerState
434 = PCS { pcs_PST = initPackageDetails,
435 pcs_insts = emptyInstEnv,
436 pcs_rules = initRules,
437 pcs_PRS = initPersistentRenamerState }
440 initPackageDetails :: PackageSymbolTable
441 initPackageDetails = extendTypeEnv emptyModuleEnv wiredInThings
443 initPersistentRenamerState :: IO PersistentRenamerState
444 = do ns <- mkSplitUniqSupply 'r'
446 PRS { prsOrig = Orig { origNames = initOrigNames,
447 origIParam = emptyFM },
448 prsDecls = emptyNameEnv,
455 initOrigNames :: FiniteMap (ModuleName,OccName) Name
456 initOrigNames = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
458 grab names = foldl add emptyFM names
459 add env name = addToFM env (moduleName (nameModule name), nameOccName name) name
463 initRules = foldl add emptyVarEnv builtinRules
465 add env (name,rule) = extendNameEnv_C add1 env name [rule]
466 add1 rules _ = rule : rules
472 writeIface this_mod old_iface new_iface
473 local_tycons local_classes inst_info
474 final_ids tidy_binds tidy_orphan_rules
476 if isNothing opt_HiDir && isNothing opt_HiFile
477 then return () -- not producing any .hi file
481 hi_suf = case opt_HiSuf of { Nothing -> "hi"; Just suf -> suf }
482 filename = case opt_HiFile of {
486 Just dir -> dir ++ '/':moduleUserString this_mod
488 Nothing -> panic "writeIface"
492 do maybe_final_iface <- checkIface old_iface full_new_iface
493 case maybe_final_iface of {
494 Nothing -> when opt_D_dump_rn_trace $
495 putStrLn "Interface file unchanged" ; -- No need to update .hi file
499 do let mod_vers_unchanged = case old_iface of
500 Just iface -> pi_vers iface == pi_vers final_iface
502 when (mod_vers_unchanged && opt_D_dump_rn_trace) $
503 putStrLn "Module version unchanged, but usages differ; hence need new hi file"
505 if_hdl <- openFile filename WriteMode
506 printForIface if_hdl (pprIface final_iface)
510 full_new_iface = completeIface new_iface local_tycons local_classes
511 inst_info final_ids tidy_binds
516 %************************************************************************
518 \subsection{Printing the interface}
520 %************************************************************************
523 pprIface (ParsedIface { pi_mod = mod, pi_vers = mod_vers, pi_orphan = orphan,
524 pi_usages = usages, pi_exports = exports,
525 pi_fixity = (fix_vers, fixities),
526 pi_insts = insts, pi_decls = decls,
527 pi_rules = (rule_vers, rules), pi_deprecs = deprecs })
528 = vcat [ ptext SLIT("__interface")
529 <+> doubleQuotes (ptext opt_InPackage)
530 <+> ppr mod <+> ppr mod_vers <+> pp_sub_vers
531 <+> (if orphan then char '!' else empty)
532 <+> int opt_HiVersion
533 <+> ptext SLIT("where")
534 , vcat (map pprExport exports)
535 , vcat (map pprUsage usages)
536 , pprFixities fixities
537 , vcat [ppr i <+> semi | i <- insts]
538 , vcat [ppr_vers v <+> ppr d <> semi | (v,d) <- decls]
543 ppr_vers v | v == initialVersion = empty
546 | fix_vers == initialVersion && rule_vers == initialVersion = empty
547 | otherwise = brackets (ppr fix_vers <+> ppr rule_vers)
550 When printing export lists, we print like this:
552 AvailTC C [C, x, y] C(x,y)
553 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
556 pprExport :: ExportItem -> SDoc
557 pprExport (mod, items)
558 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map upp_avail items) ] <> semi
560 upp_avail :: RdrAvailInfo -> SDoc
561 upp_avail (Avail name) = pprOccName name
562 upp_avail (AvailTC name []) = empty
563 upp_avail (AvailTC name ns) = hcat [pprOccName name, bang, upp_export ns']
565 bang | name `elem` ns = empty
566 | otherwise = char '|'
567 ns' = filter (/= name) ns
569 upp_export [] = empty
570 upp_export names = braces (hsep (map pprOccName names))
575 pprUsage :: ImportVersion OccName -> SDoc
576 pprUsage (m, has_orphans, is_boot, whats_imported)
577 = hsep [ptext SLIT("import"), pprModuleName m,
579 upp_import_versions whats_imported
582 pp_orphan | has_orphans = char '!'
584 pp_boot | is_boot = char '@'
587 -- Importing the whole module is indicated by an empty list
588 upp_import_versions NothingAtAll = empty
589 upp_import_versions (Everything v) = dcolon <+> int v
590 upp_import_versions (Specifically vm vf vr nvs)
591 = dcolon <+> int vm <+> int vf <+> int vr <+> hsep [ ppr n <+> int v | (n,v) <- nvs ]
596 pprFixities [] = empty
597 pprFixities fixes = hsep (map ppr fixes) <> semi
600 pprRules rules = hsep [ptext SLIT("{-## __R"), hsep (map ppr rules), ptext SLIT("##-}")]
602 pprDeprecs [] = empty
603 pprDeprecs deps = hsep [ ptext SLIT("{-## __D"), guts, ptext SLIT("##-}")]
605 guts = hsep [ ppr ie <+> doubleQuotes (ppr txt) <> semi
606 | Deprecation ie txt _ <- deps ]