[project @ 2000-10-24 10:12:16 by sewardj]
[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 ( hscMain ) where
8
9 #include "HsVersions.h"
10
11 import IO               ( hPutStr, stderr )
12 import HsSyn
13
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 )
20
21 import Rename           ( renameModule )
22
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 )
37
38 import Module           ( ModuleName, moduleNameUserString )
39 import CmdLineOpts
40 import ErrUtils         ( ghcExit, doIfSet, dumpIfSet )
41 import UniqSupply       ( mkSplitUniqSupply )
42
43 import Outputable
44 import Char             ( isSpace )
45 import StgInterp        ( runStgI )
46 import HscStats         ( ppSourceStats )
47 \end{code}
48
49
50 %************************************************************************
51 %*                                                                      *
52 \subsection{The main compiler pipeline}
53 %*                                                                      *
54 %************************************************************************
55
56 \begin{code}
57 data HscResult
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
65
66    | HscErrs PersistentCompilerState -- updated PCS
67              (Bag ErrMsg)               -- errors
68              (Bag WarnMsg)             -- warnings
69
70 hscMain
71   :: DynFlags   
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
77   -> IO HscResult
78
79 hscMain dflags core_cmds stg_cmds summary maybe_old_iface
80         output_filename mod_details pcs1 =
81
82         --------------------------  Reader  ----------------
83     show_pass "Parser"  >>
84     _scc_     "Parser"
85
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"
90                                 (ppr summary)
91
92     buf <- hGetStringBuffer True{-expand tabs-} src_filename
93
94     let glaexts | dopt Opt_GlasgowExts dflags = 1#
95                 | otherwise                   = 0#
96
97     case parse buf PState{ bol = 0#, atbol = 1#,
98                            context = [], glasgow_exts = glaexts,
99                            loc = mkSrcLoc src_filename 1 } of {
100
101         PFailed err -> return (HscErrs pcs (unitBag err) emptyBag)
102
103         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) ->
104
105     dumpIfSet (dopt_D_dump_parsed flags) "Parser" (ppr rdr_module) >>
106
107     dumpIfSet (dopt_D_source_stats flags) "Source Statistics"
108         (ppSourceStats False rdr_module)                >>
109
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 'g'       >>= \ st_uniqs  -> -- stg-to-stg passes
115     mkSplitUniqSupply 'n'       >>= \ ncg_uniqs -> -- native-code generator
116
117         --------------------------  Rename  ----------------
118     show_pass "Renamer"                         >>
119     _scc_     "Renamer"
120
121     renameModule dflags finder pcs hst rdr_module       
122                                                 >>= \ (pcs_rn, maybe_rn_stuff) ->
123     case maybe_rn_stuff of {
124         Nothing ->      -- Hurrah!  Renamer reckons that there's no need to
125                         -- go any further
126                         reportCompile mod_name "Compilation NOT required!" >>
127                         return ();
128         
129         Just (this_mod, rn_mod, 
130               old_iface, new_iface,
131               rn_name_supply, fixity_env,
132               imported_modules) ->
133                         -- Oh well, we've got to recompile for real
134
135
136         --------------------------  Typechecking ----------------
137     show_pass "TypeCheck"                               >>
138     _scc_     "TypeCheck"
139     typecheckModule dflags mod pcs hst hit pit rn_mod
140     --                tc_uniqs rn_name_supply
141     --              fixity_env rn_mod           
142                                                 >>= \ maybe_tc_stuff ->
143     case maybe_tc_stuff of {
144         Nothing -> ghcExit 1;   -- Type checker failed
145
146         Just (tc_results@(TcResults {tc_tycons  = local_tycons, 
147                                      tc_classes = local_classes, 
148                                      tc_insts   = inst_info })) ->
149
150
151         --------------------------  Desugaring ----------------
152     _scc_     "DeSugar"
153     deSugar this_mod ds_uniqs tc_results        >>= \ (desugared, rules, h_code, c_code, fe_binders) ->
154
155
156         --------------------------  Main Core-language transformations ----------------
157     _scc_     "Core2Core"
158     core2core core_cmds desugared rules         >>= \ (simplified, orphan_rules) ->
159
160         -- Do the final tidy-up
161     tidyCorePgm this_mod
162                 simplified orphan_rules         >>= \ (tidy_binds, tidy_orphan_rules) -> 
163
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
169         -- in case patterns.
170     let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds in
171
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
176
177
178
179         --------------------------  Convert to STG code -------------------------------
180     show_pass "Core2Stg"                        >>
181     _scc_     "Core2Stg"
182     let
183         stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
184     in
185
186         --------------------------  Simplify STG code -------------------------------
187     show_pass "Stg2Stg"                          >>
188     _scc_     "Stg2Stg"
189     stg2stg stg_cmds this_mod st_uniqs stg_binds >>= \ (stg_binds2, cost_centre_info) ->
190
191 #ifdef GHCI
192     runStgI local_tycons local_classes 
193                          (map fst stg_binds2)    >>= \ i_result ->
194     putStr ("\nANSWER = " ++ show i_result ++ "\n\n")
195     >>
196
197 #else
198         --------------------------  Interface file -------------------------------
199         -- Dump instance decls and type signatures into the interface file
200     _scc_     "Interface"
201     let
202         final_ids = collectFinalStgBinders (map fst stg_binds2)
203     in
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          >>
207
208
209         --------------------------  Code generation -------------------------------
210     show_pass "CodeGen"                         >>
211     _scc_     "CodeGen"
212     codeGen this_mod imported_modules
213             cost_centre_info
214             fe_binders
215             local_tycons local_classes 
216             stg_binds2                          >>= \ abstractC ->
217
218
219         --------------------------  Code output -------------------------------
220     show_pass "CodeOutput"                              >>
221     _scc_     "CodeOutput"
222     codeOutput this_mod local_tycons local_classes
223                occ_anal_tidy_binds stg_binds2
224                c_code h_code abstractC 
225                ncg_uniqs                                >>
226
227
228         --------------------------  Final report -------------------------------
229     reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
230
231 #endif
232
233
234     ghcExit 0
235     } }
236   where
237     -------------------------------------------------------------
238     -- ****** help functions:
239
240     show_pass
241       = if opt_D_show_passes
242         then \ what -> hPutStr stderr ("*** "++what++":\n")
243         else \ what -> return ()
244 \end{code}
245
246
247 %************************************************************************
248 %*                                                                      *
249 \subsection{Initial persistent state}
250 %*                                                                      *
251 %************************************************************************
252
253 \begin{code}
254 initPersistentCompilerState :: IO PersistentCompilerState
255 initPersistentCompilerState 
256 <<<<<<< HscMain.lhs
257   = do prs <- initPersistentRenamerState
258        return (
259         PCS { pcs_PST   = initPackageDetails,
260               pcs_insts = emptyInstEnv,
261               pcs_rules = emptyRuleEnv,
262               pcs_PRS   = initPersistentRenamerState 
263             }
264         )
265 =======
266   = PCS { pcs_PST   = initPackageDetails,
267           pcs_insts = emptyInstEnv,
268           pcs_rules = initRules,
269           pcs_PRS   = initPersistentRenamerState }
270 >>>>>>> 1.12
271
272 initPackageDetails :: PackageSymbolTable
273 initPackageDetails = extendTypeEnv emptyModuleEnv wiredInThings
274
275 initPersistentRenamerState :: IO PersistentRenamerState
276   = do ns <- mkSplitUniqSupply 'r'
277        return (
278         PRS { prsOrig  = Orig { origNames  = initOrigNames,
279                                origIParam = emptyFM },
280               prsDecls = emptyNameEnv,
281               prsInsts = emptyBag,
282               prsRules = emptyBag,
283               prsNS    = ns
284             }
285         )
286
287 initOrigNames :: FiniteMap (ModuleName,OccName) Name
288 initOrigNames = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
289               where
290                 grab names   = foldl add emptyFM names
291                 add env name = addToFM env (moduleName (nameModule name), nameOccName name) name
292
293
294 initRules :: RuleEnv
295 initRules = foldl add emptyVarEnv builtinRules
296           where
297             add env (name,rule) = extendNameEnv_C add1 env name [rule]
298             add1 rules _        = rule : rules
299 \end{code}
300
301
302
303 \begin{code}
304 writeIface this_mod old_iface new_iface
305            local_tycons local_classes inst_info
306            final_ids tidy_binds tidy_orphan_rules
307   = 
308     if isNothing opt_HiDir && isNothing opt_HiFile
309         then return ()  -- not producing any .hi file
310         else 
311
312     let 
313         hi_suf = case opt_HiSuf of { Nothing -> "hi"; Just suf -> suf }
314         filename = case opt_HiFile of {
315                         Just f  -> f;
316                         Nothing -> 
317                    case opt_HiDir of {
318                         Just dir -> dir ++ '/':moduleUserString this_mod 
319                                         ++ '.':hi_suf;
320                         Nothing  -> panic "writeIface"
321                 }}
322     in
323
324     do maybe_final_iface <- checkIface old_iface full_new_iface         
325        case maybe_final_iface of {
326           Nothing -> when opt_D_dump_rn_trace $
327                      putStrLn "Interface file unchanged" ;  -- No need to update .hi file
328
329           Just final_iface ->
330
331        do  let mod_vers_unchanged = case old_iface of
332                                       Just iface -> pi_vers iface == pi_vers final_iface
333                                       Nothing -> False
334            when (mod_vers_unchanged && opt_D_dump_rn_trace) $
335                 putStrLn "Module version unchanged, but usages differ; hence need new hi file"
336
337            if_hdl <- openFile filename WriteMode
338            printForIface if_hdl (pprIface final_iface)
339            hClose if_hdl
340     }   
341   where
342     full_new_iface = completeIface new_iface local_tycons local_classes
343                                              inst_info final_ids tidy_binds
344                                              tidy_orphan_rules
345 \end{code}
346
347
348 %************************************************************************
349 %*                                                                      *
350 \subsection{Printing the interface}
351 %*                                                                      *
352 %************************************************************************
353
354 \begin{code}
355 pprIface (ParsedIface { pi_mod = mod, pi_vers = mod_vers, pi_orphan = orphan,
356                         pi_usages = usages, pi_exports = exports, 
357                         pi_fixity = (fix_vers, fixities),
358                         pi_insts = insts, pi_decls = decls, 
359                         pi_rules = (rule_vers, rules), pi_deprecs = deprecs })
360  = vcat [ ptext SLIT("__interface")
361                 <+> doubleQuotes (ptext opt_InPackage)
362                 <+> ppr mod <+> ppr mod_vers <+> pp_sub_vers
363                 <+> (if orphan then char '!' else empty)
364                 <+> int opt_HiVersion
365                 <+> ptext SLIT("where")
366         , vcat (map pprExport exports)
367         , vcat (map pprUsage usages)
368         , pprFixities fixities
369         , vcat [ppr i <+> semi | i <- insts]
370         , vcat [ppr_vers v <+> ppr d <> semi | (v,d) <- decls]
371         , pprRules rules
372         , pprDeprecs deprecs
373         ]
374   where
375     ppr_vers v | v == initialVersion = empty
376                | otherwise           = int v
377     pp_sub_vers 
378         | fix_vers == initialVersion && rule_vers == initialVersion = empty
379         | otherwise = brackets (ppr fix_vers <+> ppr rule_vers)
380 \end{code}
381
382 When printing export lists, we print like this:
383         Avail   f               f
384         AvailTC C [C, x, y]     C(x,y)
385         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
386
387 \begin{code}
388 pprExport :: ExportItem -> SDoc
389 pprExport (mod, items)
390  = hsep [ ptext SLIT("__export "), ppr mod, hsep (map upp_avail items) ] <> semi
391   where
392     upp_avail :: RdrAvailInfo -> SDoc
393     upp_avail (Avail name)      = pprOccName name
394     upp_avail (AvailTC name []) = empty
395     upp_avail (AvailTC name ns) = hcat [pprOccName name, bang, upp_export ns']
396                                 where
397                                   bang | name `elem` ns = empty
398                                        | otherwise      = char '|'
399                                   ns' = filter (/= name) ns
400     
401     upp_export []    = empty
402     upp_export names = braces (hsep (map pprOccName names))
403 \end{code}
404
405
406 \begin{code}
407 pprUsage :: ImportVersion OccName -> SDoc
408 pprUsage (m, has_orphans, is_boot, whats_imported)
409   = hsep [ptext SLIT("import"), pprModuleName m, 
410           pp_orphan, pp_boot,
411           upp_import_versions whats_imported
412     ] <> semi
413   where
414     pp_orphan | has_orphans = char '!'
415               | otherwise   = empty
416     pp_boot   | is_boot     = char '@'
417               | otherwise   = empty
418
419         -- Importing the whole module is indicated by an empty list
420     upp_import_versions NothingAtAll   = empty
421     upp_import_versions (Everything v) = dcolon <+> int v
422     upp_import_versions (Specifically vm vf vr nvs)
423       = dcolon <+> int vm <+> int vf <+> int vr <+> hsep [ ppr n <+> int v | (n,v) <- nvs ]
424 \end{code}
425
426
427 \begin{code}
428 pprFixities []    = empty
429 pprFixities fixes = hsep (map ppr fixes) <> semi
430
431 pprRules []    = empty
432 pprRules rules = hsep [ptext SLIT("{-## __R"), hsep (map ppr rules), ptext SLIT("##-}")]
433
434 pprDeprecs []   = empty
435 pprDeprecs deps = hsep [ ptext SLIT("{-## __D"), guts, ptext SLIT("##-}")]
436                 where
437                   guts = hsep [ ppr ie <+> doubleQuotes (ppr txt) <> semi 
438                               | Deprecation ie txt _ <- deps ]
439 \end{code}
440
441