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
64 (Bag WarnMsg) -- warnings
66 | HscErrs PersistentCompilerState -- updated PCS
67 (Bag ErrMsg) -- errors
68 (Bag WarnMsg) -- warnings
72 -> ModSummary -- summary, including source filename
73 -> Maybe ModIFace -- old interface, if available
74 -> String -- file in which to put the output (.s, .hc, .java etc.)
75 -> HomeSymbolTable -- for home module ModDetails
76 -> PersistentCompilerState -- IN: persistent compiler state
79 hscMain dflags core_cmds stg_cmds summary maybe_old_iface
80 output_filename mod_details pcs1
82 source_unchanged :: Bool -- extracted from summary?
84 (pcs2, check_errs, (recomp_reqd, maybe_checked_iface))
85 <- checkOldIface dflags finder hit hst pcs1 mod source_unchanged
88 -- test check_errs and give up if a problem happened
89 what_next = if recomp_reqd then hscRecomp else hscNoRecomp
92 what_next dflags core_cmds stg_cmds summary hit hst
93 pcs2 maybe_checked_iface
95 hscNoRecomp = panic "hscNoRecomp"
97 hscRecomp dflags core_cmds stg_cmds summary hit hst pcs maybe_old_iface
99 -- parsed :: RdrNameHsModule
100 parsed <- parseModule summary
101 -- check for parse errors
103 (pcs_rn, maybe_rn_result)
104 <- renameModule dflags finder hit hst pcs mod parsed
106 -- check maybe_rn_result for failure
108 (new_iface, rn_hs_decls) = unJust maybe_rn_result
111 <- typecheckModule dflags mod pcs hst hit pit rn_hs_decls
113 -- check maybe_tc_result for failure
114 let tc_result = unJust maybe_tc_result
115 let tc_pcs = tc_pcs tc_result
116 let tc_env = tc_env tc_result
117 let tc_binds = tc_binds tc_result
118 let local_tycons = tc_tycons tc_result
119 let local_classes = tc_classes tc_result
121 -- desugar, simplify and tidy, to create the unfoldings
122 -- why is this IO-typed?
123 (tidy_binds, orphan_rules, fe_binders, h_code, c_code) -- return modDetails?
124 <- dsThenSimplThenTidy dflags mod tc_result rule_base ds_uniqs
126 -- convert to Stg; needed for binders
127 (stg_binds, cost_centre_info, top_level_ids)
128 <- myCoreToStg c2s_uniqs st_uniqs this_mod tidy_binds
130 -- cook up a new ModDetails now we (finally) have all the bits
131 let new_details = completeModDetails tc_env tidy_binds top_level_ids orphan_rules
133 -- and possibly create a new ModIface
134 let maybe_final_iface = completeIface maybe_old_iface new_iface new_details
136 -- do the rest of code generation/emission
137 -- this is obviously nonsensical: FIX
138 (unlinkeds, stub_h_filename, stub_c_filename)
139 <- restOfCodeGeneration this_mod imported_modules cost_centre_info
140 fe_binders local_tycons local_classes stg_binds
142 -- and the answer is ...
143 return (HscOK new_details maybe_final_iface stub_h_filename stub_c_filename
144 unlinkeds tc_pcs (unionBags rn_warns tc_warns))
147 restOfCodeGeneration this_mod imported_modules cost_centre_info
148 fe_binders local_tycons local_classes stg_binds
149 = do -------------------------- Code generation -------------------------------
152 abstractC <- codeGen this_mod imported_modules
153 cost_centre_info fe_binders
154 local_tycons local_classes stg_binds
156 -------------------------- Code output -------------------------------
157 show_pass "CodeOutput"
158 -- _scc_ "CodeOutput"
159 (maybe_stub_h_name, maybe_stub_c_name)
160 <- codeOutput this_mod local_tycons local_classes
161 occ_anal_tidy_binds stg_binds2
162 c_code h_code abstractC ncg_uniqs
164 -- this is obviously nonsensical: FIX
165 return (maybe_stub_h_name, maybe_stub_c_name, [])
168 dsThenSimplThenTidy dflags mod tc_result rule_base ds_uniqs
169 = do -------------------------- Desugaring ----------------
171 (desugared, rules, h_code, c_code, fe_binders)
172 <- deSugar this_mod ds_uniqs tc_results
174 -------------------------- Main Core-language transformations ----------------
176 (simplified, orphan_rules) <- core2core core_cmds desugared rules
178 -- Do the final tidy-up
179 (tidy_binds, tidy_orphan_rules)
180 <- tidyCorePgm this_mod simplified orphan_rules
182 return (tidy_binds, tidy_orphan_rules, fe_binders, h_code, c_code)
186 myCoreToStg c2s_uniqs st_uniqs this_mod tidy_binds
187 = do let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
189 () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
190 -- TEMP: the above call zaps some space usage allocated by the
191 -- simplifier, which for reasons I don't understand, persists
192 -- thoroughout code generation
196 let stg_binds = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
200 (stg_binds2, cost_centre_info) <- stg2stg stg_cmds this_mod st_uniqs stg_binds
201 let final_ids = collectFinalStgBinders (map fst stg_binds2)
203 return (stg_binds2, cost_centre_info, final_ids)
207 -------------------------- Reader ----------------
208 show_pass "Parser" >>
211 let src_filename -- name of the preprocessed source file
212 = case ms_ppsource summary of
213 Just (filename, fingerprint) -> filename
214 Nothing -> pprPanic "hscMain:summary is not of a source module"
217 buf <- hGetStringBuffer True{-expand tabs-} src_filename
219 let glaexts | dopt Opt_GlasgowExts dflags = 1#
222 case parse buf PState{ bol = 0#, atbol = 1#,
223 context = [], glasgow_exts = glaexts,
224 loc = mkSrcLoc src_filename 1 } of {
226 PFailed err -> return (HscErrs pcs (unitBag err) emptyBag)
228 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) ->
230 dumpIfSet (dopt_D_dump_parsed flags) "Parser" (ppr rdr_module) >>
232 dumpIfSet (dopt_D_source_stats flags) "Source Statistics"
233 (ppSourceStats False rdr_module) >>
235 -- UniqueSupplies for later use (these are the only lower case uniques)
236 mkSplitUniqSupply 'd' >>= \ ds_uniqs -> -- desugarer
237 mkSplitUniqSupply 'r' >>= \ ru_uniqs -> -- rules
238 mkSplitUniqSupply 'c' >>= \ c2s_uniqs -> -- core-to-stg
239 mkSplitUniqSupply 'g' >>= \ st_uniqs -> -- stg-to-stg passes
240 mkSplitUniqSupply 'n' >>= \ ncg_uniqs -> -- native-code generator
242 -------------------------- Rename ----------------
243 show_pass "Renamer" >>
246 renameModule dflags finder pcs hst rdr_module
247 >>= \ (pcs_rn, maybe_rn_stuff) ->
248 case maybe_rn_stuff of {
249 Nothing -> -- Hurrah! Renamer reckons that there's no need to
251 reportCompile mod_name "Compilation NOT required!" >>
254 Just (this_mod, rn_mod,
255 old_iface, new_iface,
256 rn_name_supply, fixity_env,
258 -- Oh well, we've got to recompile for real
261 -------------------------- Typechecking ----------------
262 show_pass "TypeCheck" >>
264 typecheckModule dflags mod pcs hst hit pit rn_mod
265 -- tc_uniqs rn_name_supply
267 >>= \ maybe_tc_stuff ->
268 case maybe_tc_stuff of {
269 Nothing -> ghcExit 1; -- Type checker failed
271 Just (tc_results@(TcResults {tc_tycons = local_tycons,
272 tc_classes = local_classes,
273 tc_insts = inst_info })) ->
276 -------------------------- Desugaring ----------------
278 deSugar this_mod ds_uniqs tc_results >>= \ (desugared, rules, h_code, c_code, fe_binders) ->
281 -------------------------- Main Core-language transformations ----------------
283 core2core core_cmds desugared rules >>= \ (simplified, orphan_rules) ->
285 -- Do the final tidy-up
287 simplified orphan_rules >>= \ (tidy_binds, tidy_orphan_rules) ->
289 -- Run the occurrence analyser one last time, so that
290 -- dead binders get dead-binder info. This is exploited by
291 -- code generators to avoid spitting out redundant bindings.
292 -- The occurrence-zapping in Simplify.simplCaseBinder means
293 -- that the Simplifier nukes useful dead-var stuff especially
295 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds in
297 coreBindsSize occ_anal_tidy_binds `seq`
298 -- TEMP: the above call zaps some space usage allocated by the
299 -- simplifier, which for reasons I don't understand, persists
300 -- thoroughout code generation
304 -------------------------- Convert to STG code -------------------------------
305 show_pass "Core2Stg" >>
308 stg_binds = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
311 -------------------------- Simplify STG code -------------------------------
312 show_pass "Stg2Stg" >>
314 stg2stg stg_cmds this_mod st_uniqs stg_binds >>= \ (stg_binds2, cost_centre_info) ->
317 runStgI local_tycons local_classes
318 (map fst stg_binds2) >>= \ i_result ->
319 putStr ("\nANSWER = " ++ show i_result ++ "\n\n")
323 -------------------------- Interface file -------------------------------
324 -- Dump instance decls and type signatures into the interface file
327 final_ids = collectFinalStgBinders (map fst stg_binds2)
329 writeIface this_mod old_iface new_iface
330 local_tycons local_classes inst_info
331 final_ids occ_anal_tidy_binds tidy_orphan_rules >>
334 -------------------------- Code generation -------------------------------
335 show_pass "CodeGen" >>
337 codeGen this_mod imported_modules
340 local_tycons local_classes
341 stg_binds2 >>= \ abstractC ->
344 -------------------------- Code output -------------------------------
345 show_pass "CodeOutput" >>
347 codeOutput this_mod local_tycons local_classes
348 occ_anal_tidy_binds stg_binds2
349 c_code h_code abstractC
353 -------------------------- Final report -------------------------------
354 reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
362 -------------------------------------------------------------
363 -- ****** help functions:
366 = if opt_D_show_passes
367 then \ what -> hPutStr stderr ("*** "++what++":\n")
368 else \ what -> return ()
374 %************************************************************************
376 \subsection{Initial persistent state}
378 %************************************************************************
381 initPersistentCompilerState :: IO PersistentCompilerState
382 initPersistentCompilerState
384 = do prs <- initPersistentRenamerState
386 PCS { pcs_PST = initPackageDetails,
387 pcs_insts = emptyInstEnv,
388 pcs_rules = emptyRuleEnv,
389 pcs_PRS = initPersistentRenamerState
393 = PCS { pcs_PST = initPackageDetails,
394 pcs_insts = emptyInstEnv,
395 pcs_rules = initRules,
396 pcs_PRS = initPersistentRenamerState }
399 initPackageDetails :: PackageSymbolTable
400 initPackageDetails = extendTypeEnv emptyModuleEnv wiredInThings
402 initPersistentRenamerState :: IO PersistentRenamerState
403 = do ns <- mkSplitUniqSupply 'r'
405 PRS { prsOrig = Orig { origNames = initOrigNames,
406 origIParam = emptyFM },
407 prsDecls = emptyNameEnv,
414 initOrigNames :: FiniteMap (ModuleName,OccName) Name
415 initOrigNames = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
417 grab names = foldl add emptyFM names
418 add env name = addToFM env (moduleName (nameModule name), nameOccName name) name
422 initRules = foldl add emptyVarEnv builtinRules
424 add env (name,rule) = extendNameEnv_C add1 env name [rule]
425 add1 rules _ = rule : rules
431 writeIface this_mod old_iface new_iface
432 local_tycons local_classes inst_info
433 final_ids tidy_binds tidy_orphan_rules
435 if isNothing opt_HiDir && isNothing opt_HiFile
436 then return () -- not producing any .hi file
440 hi_suf = case opt_HiSuf of { Nothing -> "hi"; Just suf -> suf }
441 filename = case opt_HiFile of {
445 Just dir -> dir ++ '/':moduleUserString this_mod
447 Nothing -> panic "writeIface"
451 do maybe_final_iface <- checkIface old_iface full_new_iface
452 case maybe_final_iface of {
453 Nothing -> when opt_D_dump_rn_trace $
454 putStrLn "Interface file unchanged" ; -- No need to update .hi file
458 do let mod_vers_unchanged = case old_iface of
459 Just iface -> pi_vers iface == pi_vers final_iface
461 when (mod_vers_unchanged && opt_D_dump_rn_trace) $
462 putStrLn "Module version unchanged, but usages differ; hence need new hi file"
464 if_hdl <- openFile filename WriteMode
465 printForIface if_hdl (pprIface final_iface)
469 full_new_iface = completeIface new_iface local_tycons local_classes
470 inst_info final_ids tidy_binds
475 %************************************************************************
477 \subsection{Printing the interface}
479 %************************************************************************
482 pprIface (ParsedIface { pi_mod = mod, pi_vers = mod_vers, pi_orphan = orphan,
483 pi_usages = usages, pi_exports = exports,
484 pi_fixity = (fix_vers, fixities),
485 pi_insts = insts, pi_decls = decls,
486 pi_rules = (rule_vers, rules), pi_deprecs = deprecs })
487 = vcat [ ptext SLIT("__interface")
488 <+> doubleQuotes (ptext opt_InPackage)
489 <+> ppr mod <+> ppr mod_vers <+> pp_sub_vers
490 <+> (if orphan then char '!' else empty)
491 <+> int opt_HiVersion
492 <+> ptext SLIT("where")
493 , vcat (map pprExport exports)
494 , vcat (map pprUsage usages)
495 , pprFixities fixities
496 , vcat [ppr i <+> semi | i <- insts]
497 , vcat [ppr_vers v <+> ppr d <> semi | (v,d) <- decls]
502 ppr_vers v | v == initialVersion = empty
505 | fix_vers == initialVersion && rule_vers == initialVersion = empty
506 | otherwise = brackets (ppr fix_vers <+> ppr rule_vers)
509 When printing export lists, we print like this:
511 AvailTC C [C, x, y] C(x,y)
512 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
515 pprExport :: ExportItem -> SDoc
516 pprExport (mod, items)
517 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map upp_avail items) ] <> semi
519 upp_avail :: RdrAvailInfo -> SDoc
520 upp_avail (Avail name) = pprOccName name
521 upp_avail (AvailTC name []) = empty
522 upp_avail (AvailTC name ns) = hcat [pprOccName name, bang, upp_export ns']
524 bang | name `elem` ns = empty
525 | otherwise = char '|'
526 ns' = filter (/= name) ns
528 upp_export [] = empty
529 upp_export names = braces (hsep (map pprOccName names))
534 pprUsage :: ImportVersion OccName -> SDoc
535 pprUsage (m, has_orphans, is_boot, whats_imported)
536 = hsep [ptext SLIT("import"), pprModuleName m,
538 upp_import_versions whats_imported
541 pp_orphan | has_orphans = char '!'
543 pp_boot | is_boot = char '@'
546 -- Importing the whole module is indicated by an empty list
547 upp_import_versions NothingAtAll = empty
548 upp_import_versions (Everything v) = dcolon <+> int v
549 upp_import_versions (Specifically vm vf vr nvs)
550 = dcolon <+> int vm <+> int vf <+> int vr <+> hsep [ ppr n <+> int v | (n,v) <- nvs ]
555 pprFixities [] = empty
556 pprFixities fixes = hsep (map ppr fixes) <> semi
559 pprRules rules = hsep [ptext SLIT("{-## __R"), hsep (map ppr rules), ptext SLIT("##-}")]
561 pprDeprecs [] = empty
562 pprDeprecs deps = hsep [ ptext SLIT("{-## __D"), guts, ptext SLIT("##-}")]
564 guts = hsep [ ppr ie <+> doubleQuotes (ppr txt) <> semi
565 | Deprecation ie txt _ <- deps ]