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 flags core_cmds stg_cmds summary maybe_old_iface
80 output_filename mod_details pcs1 =
82 -------------------------- Reader ----------------
86 let src_filename -- name of the preprocessed source file
87 = case ms_ppsource summary of
88 Just (filename, fingerprint) -> filename
89 Nothing -> pprPanic "hscMain:summary is not of a source module"
92 buf <- hGetStringBuffer True{-expand tabs-} src_filename
94 let glaexts | opt_GlasgowExts = 1#
97 case parse buf PState{ bol = 0#, atbol = 1#,
98 context = [], glasgow_exts = glaexts,
99 loc = mkSrcLoc src_filename 1 } of {
101 PFailed err -> return (CompErrs pcs err)
103 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) ->
105 dumpIfSet (dopt_D_dump_parsed flags) "Parser" (ppr rdr_module) >>
107 dumpIfSet (dopt_D_source_stats flags) "Source Statistics"
108 (ppSourceStats False rdr_module) >>
110 -- UniqueSupplies for later use (these are the only lower case uniques)
111 mkSplitUniqSupply 'd' >>= \ ds_uniqs -> -- desugarer
112 mkSplitUniqSupply 'r' >>= \ ru_uniqs -> -- rules
113 mkSplitUniqSupply 'c' >>= \ c2s_uniqs -> -- core-to-stg
114 mkSplitUniqSupply 'u' >>= \ tidy_uniqs -> -- tidy up
115 mkSplitUniqSupply 'g' >>= \ st_uniqs -> -- stg-to-stg passes
116 mkSplitUniqSupply 'n' >>= \ ncg_uniqs -> -- native-code generator
118 -------------------------- Rename ----------------
119 show_pass "Renamer" >>
122 renameModule rn_uniqs rdr_module >>= \ maybe_rn_stuff ->
123 case maybe_rn_stuff of {
124 Nothing -> -- Hurrah! Renamer reckons that there's no need to
126 reportCompile mod_name "Compilation NOT required!" >>
129 Just (this_mod, rn_mod,
130 old_iface, new_iface,
131 rn_name_supply, fixity_env,
133 -- Oh well, we've got to recompile for real
136 -------------------------- Typechecking ----------------
137 show_pass "TypeCheck" >>
139 typecheckModule dflags mod pcs hst hit pit rn_mod
140 -- tc_uniqs rn_name_supply
142 >>= \ maybe_tc_stuff ->
143 case maybe_tc_stuff of {
144 Nothing -> ghcExit 1; -- Type checker failed
146 Just (tc_results@(TcResults {tc_tycons = local_tycons,
147 tc_classes = local_classes,
148 tc_insts = inst_info })) ->
151 -------------------------- Desugaring ----------------
153 deSugar this_mod ds_uniqs tc_results >>= \ (desugared, rules, h_code, c_code, fe_binders) ->
156 -------------------------- Main Core-language transformations ----------------
158 core2core core_cmds desugared rules >>= \ (simplified, orphan_rules) ->
160 -- Do the final tidy-up
161 tidyCorePgm tidy_uniqs this_mod
162 simplified orphan_rules >>= \ (tidy_binds, tidy_orphan_rules) ->
164 -- Run the occurrence analyser one last time, so that
165 -- dead binders get dead-binder info. This is exploited by
166 -- code generators to avoid spitting out redundant bindings.
167 -- The occurrence-zapping in Simplify.simplCaseBinder means
168 -- that the Simplifier nukes useful dead-var stuff especially
170 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds in
172 coreBindsSize occ_anal_tidy_binds `seq`
173 -- TEMP: the above call zaps some space usage allocated by the
174 -- simplifier, which for reasons I don't understand, persists
175 -- thoroughout code generation
179 -------------------------- Convert to STG code -------------------------------
180 show_pass "Core2Stg" >>
183 stg_binds = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
186 -------------------------- Simplify STG code -------------------------------
187 show_pass "Stg2Stg" >>
189 stg2stg stg_cmds this_mod st_uniqs stg_binds >>= \ (stg_binds2, cost_centre_info) ->
192 runStgI local_tycons local_classes
193 (map fst stg_binds2) >>= \ i_result ->
194 putStr ("\nANSWER = " ++ show i_result ++ "\n\n")
198 -------------------------- Interface file -------------------------------
199 -- Dump instance decls and type signatures into the interface file
202 final_ids = collectFinalStgBinders (map fst stg_binds2)
204 writeIface this_mod old_iface new_iface
205 local_tycons local_classes inst_info
206 final_ids occ_anal_tidy_binds tidy_orphan_rules >>
209 -------------------------- Code generation -------------------------------
210 show_pass "CodeGen" >>
212 codeGen this_mod imported_modules
215 local_tycons local_classes
216 stg_binds2 >>= \ abstractC ->
219 -------------------------- Code output -------------------------------
220 show_pass "CodeOutput" >>
222 codeOutput this_mod local_tycons local_classes
223 occ_anal_tidy_binds stg_binds2
224 c_code h_code abstractC
228 -------------------------- Final report -------------------------------
229 reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
237 -------------------------------------------------------------
238 -- ****** help functions:
241 = if opt_D_show_passes
242 then \ what -> hPutStr stderr ("*** "++what++":\n")
243 else \ what -> return ()
247 %************************************************************************
249 \subsection{Initial persistent state}
251 %************************************************************************
254 initPersistentCompilerState :: PersistentCompilerState
255 initPersistentCompilerState
256 = PCS { pcs_PST = initPackageDetails,
257 pcs_insts = emptyInstEnv,
258 pcs_rules = initRules,
259 pcs_PRS = initPersistentRenamerState }
261 initPackageDetails :: PackageSymbolTable
262 initPackageDetails = extendTypeEnv emptyModuleEnv wiredInThings
264 initPersistentRenamerState :: PersistentRenamerState
265 = PRS { prsOrig = Orig { origNames = initOrigNames,
266 origIParam = emptyFM },
267 prsDecls = emptyNameEnv,
272 initOrigNames :: FiniteMap (ModuleName,OccName) Name
273 initOrigNames = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
275 grab names = foldl add emptyFM names
276 add env name = addToFM env (moduleName (nameModule name), nameOccName name) name
280 initRules = foldl add emptyVarEnv builtinRules
282 add env (name,rule) = extendNameEnv_C add1 env name [rule]
283 add1 rules _ = rule : rules
289 writeIface this_mod old_iface new_iface
290 local_tycons local_classes inst_info
291 final_ids tidy_binds tidy_orphan_rules
293 if isNothing opt_HiDir && isNothing opt_HiFile
294 then return () -- not producing any .hi file
298 hi_suf = case opt_HiSuf of { Nothing -> "hi"; Just suf -> suf }
299 filename = case opt_HiFile of {
303 Just dir -> dir ++ '/':moduleUserString this_mod
305 Nothing -> panic "writeIface"
309 do maybe_final_iface <- checkIface old_iface full_new_iface
310 case maybe_final_iface of {
311 Nothing -> when opt_D_dump_rn_trace $
312 putStrLn "Interface file unchanged" ; -- No need to update .hi file
316 do let mod_vers_unchanged = case old_iface of
317 Just iface -> pi_vers iface == pi_vers final_iface
319 when (mod_vers_unchanged && opt_D_dump_rn_trace) $
320 putStrLn "Module version unchanged, but usages differ; hence need new hi file"
322 if_hdl <- openFile filename WriteMode
323 printForIface if_hdl (pprIface final_iface)
327 full_new_iface = completeIface new_iface local_tycons local_classes
328 inst_info final_ids tidy_binds
333 %************************************************************************
335 \subsection{Printing the interface}
337 %************************************************************************
340 pprIface (ParsedIface { pi_mod = mod, pi_vers = mod_vers, pi_orphan = orphan,
341 pi_usages = usages, pi_exports = exports,
342 pi_fixity = (fix_vers, fixities),
343 pi_insts = insts, pi_decls = decls,
344 pi_rules = (rule_vers, rules), pi_deprecs = deprecs })
345 = vcat [ ptext SLIT("__interface")
346 <+> doubleQuotes (ptext opt_InPackage)
347 <+> ppr mod <+> ppr mod_vers <+> pp_sub_vers
348 <+> (if orphan then char '!' else empty)
349 <+> int opt_HiVersion
350 <+> ptext SLIT("where")
351 , vcat (map pprExport exports)
352 , vcat (map pprUsage usages)
353 , pprFixities fixities
354 , vcat [ppr i <+> semi | i <- insts]
355 , vcat [ppr_vers v <+> ppr d <> semi | (v,d) <- decls]
360 ppr_vers v | v == initialVersion = empty
363 | fix_vers == initialVersion && rule_vers == initialVersion = empty
364 | otherwise = brackets (ppr fix_vers <+> ppr rule_vers)
367 When printing export lists, we print like this:
369 AvailTC C [C, x, y] C(x,y)
370 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
373 pprExport :: ExportItem -> SDoc
374 pprExport (mod, items)
375 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map upp_avail items) ] <> semi
377 upp_avail :: RdrAvailInfo -> SDoc
378 upp_avail (Avail name) = pprOccName name
379 upp_avail (AvailTC name []) = empty
380 upp_avail (AvailTC name ns) = hcat [pprOccName name, bang, upp_export ns']
382 bang | name `elem` ns = empty
383 | otherwise = char '|'
384 ns' = filter (/= name) ns
386 upp_export [] = empty
387 upp_export names = braces (hsep (map pprOccName names))
392 pprUsage :: ImportVersion OccName -> SDoc
393 pprUsage (m, has_orphans, is_boot, whats_imported)
394 = hsep [ptext SLIT("import"), pprModuleName m,
396 upp_import_versions whats_imported
399 pp_orphan | has_orphans = char '!'
401 pp_boot | is_boot = char '@'
404 -- Importing the whole module is indicated by an empty list
405 upp_import_versions NothingAtAll = empty
406 upp_import_versions (Everything v) = dcolon <+> int v
407 upp_import_versions (Specifically vm vf vr nvs)
408 = dcolon <+> int vm <+> int vf <+> int vr <+> hsep [ ppr n <+> int v | (n,v) <- nvs ]
413 pprFixities [] = empty
414 pprFixities fixes = hsep (map ppr fixes) <> semi
417 pprRules rules = hsep [ptext SLIT("{-## __R"), hsep (map ppr rules), ptext SLIT("##-}")]
419 pprDeprecs [] = empty
420 pprDeprecs deps = hsep [ ptext SLIT("{-## __D"), guts, ptext SLIT("##-}")]
422 guts = hsep [ ppr ie <+> doubleQuotes (ppr txt) <> semi
423 | Deprecation ie txt _ <- deps ]