[project @ 2000-10-25 12:47:43 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],ItblEnv)) -- interpreted code, if any
63              PersistentCompilerState -- updated PCS
64
65    | HscFail PersistentCompilerState -- updated PCS
66         -- no errors or warnings; the individual passes
67         -- (parse/rename/typecheck) print messages themselves
68
69 hscMain
70   :: DynFlags   
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
76   -> IO HscResult
77
78 hscMain dflags core_cmds stg_cmds summary maybe_old_iface
79         output_filename mod_details pcs1 
80  = do
81       source_unchanged :: Bool -- extracted from summary?
82
83       (pcs2, check_errs, (recomp_reqd, maybe_checked_iface))
84          <- checkOldIface dflags finder hit hst pcs1 mod source_unchanged
85                           maybe_old_iface
86
87       -- test check_errs and give up if a problem happened
88       what_next = if recomp_reqd then hscRecomp else hscNoRecomp
89
90       return $
91          what_next dflags core_cmds stg_cmds summary hit hst 
92                    pcs2 maybe_checked_iface
93
94 hscNoRecomp = panic "hscNoRecomp"
95
96 hscRecomp dflags core_cmds stg_cmds summary hit hst pcs maybe_old_iface
97  = do {
98       -- what target are we shooting for?
99       let toInterp = dopt_HscLang dflags == HscInterpreted;
100
101       -- PARSE
102       maybe_parsed <- myParseModule dflags summary;
103       case maybe_parsed of {
104          Nothing -> return (HscFail pcs);
105          Just rdr_module -> do {
106
107       -- RENAME
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 {
113
114       -- TYPECHECK
115       maybe_tc_result
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 {
120
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
126
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
131
132       -- CONVERT TO STG
133       (stg_binds, cost_centre_info, top_level_ids) 
134          <- myCoreToStg c2s_uniqs st_uniqs this_mod tidy_binds
135
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
138
139       -- and possibly create a new ModIface
140       let maybe_final_iface = completeIface maybe_old_iface new_iface new_details 
141
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
147
148       -- and the answer is ...
149       return (HscOK new_details maybe_final_iface 
150                     maybe_stub_h_filename maybe_stub_c_filename
151                     maybe_ibinds pcs_tc)
152       }}}}}}}
153
154
155 myParseModule dflags summary
156  = do --------------------------  Reader  ----------------
157       show_pass "Parser"
158       -- _scc_     "Parser"
159
160       let src_filename -- name of the preprocessed source file
161          = case ms_ppsource summary of
162               Just (filename, fingerprint) -> filename
163               Nothing -> pprPanic "myParseModule:summary is not of a source module"
164                                   (ppr summary)
165
166       buf <- hGetStringBuffer True{-expand tabs-} src_filename
167
168       let glaexts | dopt Opt_GlasgowExts dflags = 1#
169                   | otherwise                 = 0#
170
171       case parse buf PState{ bol = 0#, atbol = 1#,
172                              context = [], glasgow_exts = glaexts,
173                              loc = mkSrcLoc src_filename 1 } of {
174
175         PFailed err -> do hPutStrLn stderr (showSDoc err)
176                           return Nothing
177         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) ->
178
179       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module)
180       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
181                            (ppSourceStats False rdr_module)
182
183       return (Just rdr_module)
184
185
186 restOfCodeGeneration toInterp this_mod imported_modules cost_centre_info 
187                      fe_binders local_tycons local_classes stg_binds
188  | toInterp
189  = return (Nothing, Nothing, stgToInterpSyn stg_binds local_tycons local_classes)
190
191  | otherwise
192  = do --------------------------  Code generation -------------------------------
193       show_pass "CodeGen"
194       -- _scc_     "CodeGen"
195       abstractC <- codeGen this_mod imported_modules
196                            cost_centre_info fe_binders
197                            local_tycons local_classes stg_binds
198
199       --------------------------  Code output -------------------------------
200       show_pass "CodeOutput"
201       -- _scc_     "CodeOutput"
202       (maybe_stub_h_name, maybe_stub_c_name)
203          <- codeOutput this_mod local_tycons local_classes
204                        occ_anal_tidy_binds stg_binds2
205                        c_code h_code abstractC ncg_uniqs
206
207       return (maybe_stub_h_name, maybe_stub_c_name, [{-UnlinkedIBind-}])
208
209
210 dsThenSimplThenTidy dflags mod tc_result rule_base ds_uniqs
211  = do --------------------------  Desugaring ----------------
212       -- _scc_     "DeSugar"
213       (desugared, rules, h_code, c_code, fe_binders) 
214          <- deSugar this_mod ds_uniqs tc_results
215
216       --------------------------  Main Core-language transformations ----------------
217       -- _scc_     "Core2Core"
218       (simplified, orphan_rules)  <- core2core core_cmds desugared rules
219
220       -- Do the final tidy-up
221       (tidy_binds, tidy_orphan_rules) 
222          <- tidyCorePgm this_mod simplified orphan_rules
223       
224       return (tidy_binds, tidy_orphan_rules, fe_binders, h_code, c_code)
225
226
227
228 myCoreToStg c2s_uniqs st_uniqs this_mod tidy_binds
229  = do let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
230
231       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
232       -- TEMP: the above call zaps some space usage allocated by the
233       -- simplifier, which for reasons I don't understand, persists
234       -- thoroughout code generation
235
236       show_pass "Core2Stg"
237       -- _scc_     "Core2Stg"
238       let stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
239
240       show_pass "Stg2Stg"
241       -- _scc_     "Stg2Stg"
242       (stg_binds2, cost_centre_info) <- stg2stg stg_cmds this_mod st_uniqs stg_binds
243       let final_ids = collectFinalStgBinders (map fst stg_binds2)
244
245       return (stg_binds2, cost_centre_info, final_ids)
246
247 #if 0
248 -- BEGIN old stuff
249         --------------------------  Reader  ----------------
250     show_pass "Parser"  >>
251     _scc_     "Parser"
252
253     let src_filename -- name of the preprocessed source file
254        = case ms_ppsource summary of
255             Just (filename, fingerprint) -> filename
256             Nothing -> pprPanic "hscMain:summary is not of a source module"
257                                 (ppr summary)
258
259     buf <- hGetStringBuffer True{-expand tabs-} src_filename
260
261     let glaexts | dopt Opt_GlasgowExts dflags = 1#
262                 | otherwise                   = 0#
263
264     case parse buf PState{ bol = 0#, atbol = 1#,
265                            context = [], glasgow_exts = glaexts,
266                            loc = mkSrcLoc src_filename 1 } of {
267
268         PFailed err -> return (HscErrs pcs (unitBag err) emptyBag)
269
270         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) ->
271
272     dumpIfSet (dopt_D_dump_parsed flags) "Parser" (ppr rdr_module) >>
273
274     dumpIfSet (dopt_D_source_stats flags) "Source Statistics"
275         (ppSourceStats False rdr_module)                >>
276
277     -- UniqueSupplies for later use (these are the only lower case uniques)
278     mkSplitUniqSupply 'd'       >>= \ ds_uniqs  -> -- desugarer
279     mkSplitUniqSupply 'r'       >>= \ ru_uniqs  -> -- rules
280     mkSplitUniqSupply 'c'       >>= \ c2s_uniqs -> -- core-to-stg
281     mkSplitUniqSupply 'g'       >>= \ st_uniqs  -> -- stg-to-stg passes
282     mkSplitUniqSupply 'n'       >>= \ ncg_uniqs -> -- native-code generator
283
284         --------------------------  Rename  ----------------
285     show_pass "Renamer"                         >>
286     _scc_     "Renamer"
287
288     renameModule dflags finder pcs hst rdr_module       
289                                                 >>= \ (pcs_rn, maybe_rn_stuff) ->
290     case maybe_rn_stuff of {
291         Nothing ->      -- Hurrah!  Renamer reckons that there's no need to
292                         -- go any further
293                         reportCompile mod_name "Compilation NOT required!" >>
294                         return ();
295         
296         Just (this_mod, rn_mod, 
297               old_iface, new_iface,
298               rn_name_supply, fixity_env,
299               imported_modules) ->
300                         -- Oh well, we've got to recompile for real
301
302
303         --------------------------  Typechecking ----------------
304     show_pass "TypeCheck"                               >>
305     _scc_     "TypeCheck"
306     typecheckModule dflags mod pcs hst hit pit rn_mod
307     --                tc_uniqs rn_name_supply
308     --              fixity_env rn_mod           
309                                                 >>= \ maybe_tc_stuff ->
310     case maybe_tc_stuff of {
311         Nothing -> ghcExit 1;   -- Type checker failed
312
313         Just (tc_results@(TcResults {tc_tycons  = local_tycons, 
314                                      tc_classes = local_classes, 
315                                      tc_insts   = inst_info })) ->
316
317
318         --------------------------  Desugaring ----------------
319     _scc_     "DeSugar"
320     deSugar this_mod ds_uniqs tc_results        >>= \ (desugared, rules, h_code, c_code, fe_binders) ->
321
322
323         --------------------------  Main Core-language transformations ----------------
324     _scc_     "Core2Core"
325     core2core core_cmds desugared rules         >>= \ (simplified, orphan_rules) ->
326
327         -- Do the final tidy-up
328     tidyCorePgm this_mod
329                 simplified orphan_rules         >>= \ (tidy_binds, tidy_orphan_rules) -> 
330
331         -- Run the occurrence analyser one last time, so that
332         -- dead binders get dead-binder info.  This is exploited by
333         -- code generators to avoid spitting out redundant bindings.
334         -- The occurrence-zapping in Simplify.simplCaseBinder means
335         -- that the Simplifier nukes useful dead-var stuff especially
336         -- in case patterns.
337     let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds in
338
339     coreBindsSize occ_anal_tidy_binds `seq`
340 --      TEMP: the above call zaps some space usage allocated by the
341 --      simplifier, which for reasons I don't understand, persists
342 --      thoroughout code generation
343
344
345
346         --------------------------  Convert to STG code -------------------------------
347     show_pass "Core2Stg"                        >>
348     _scc_     "Core2Stg"
349     let
350         stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
351     in
352
353         --------------------------  Simplify STG code -------------------------------
354     show_pass "Stg2Stg"                          >>
355     _scc_     "Stg2Stg"
356     stg2stg stg_cmds this_mod st_uniqs stg_binds >>= \ (stg_binds2, cost_centre_info) ->
357
358 #ifdef GHCI
359     runStgI local_tycons local_classes 
360                          (map fst stg_binds2)    >>= \ i_result ->
361     putStr ("\nANSWER = " ++ show i_result ++ "\n\n")
362     >>
363
364 #else
365         --------------------------  Interface file -------------------------------
366         -- Dump instance decls and type signatures into the interface file
367     _scc_     "Interface"
368     let
369         final_ids = collectFinalStgBinders (map fst stg_binds2)
370     in
371     writeIface this_mod old_iface new_iface
372                local_tycons local_classes inst_info
373                final_ids occ_anal_tidy_binds tidy_orphan_rules          >>
374
375
376         --------------------------  Code generation -------------------------------
377     show_pass "CodeGen"                         >>
378     _scc_     "CodeGen"
379     codeGen this_mod imported_modules
380             cost_centre_info
381             fe_binders
382             local_tycons local_classes 
383             stg_binds2                          >>= \ abstractC ->
384
385
386         --------------------------  Code output -------------------------------
387     show_pass "CodeOutput"                              >>
388     _scc_     "CodeOutput"
389     codeOutput this_mod local_tycons local_classes
390                occ_anal_tidy_binds stg_binds2
391                c_code h_code abstractC 
392                ncg_uniqs                                >>
393
394
395         --------------------------  Final report -------------------------------
396     reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
397
398 #endif
399
400
401     ghcExit 0
402     } }
403   where
404     -------------------------------------------------------------
405     -- ****** help functions:
406
407     show_pass
408       = if opt_D_show_passes
409         then \ what -> hPutStr stderr ("*** "++what++":\n")
410         else \ what -> return ()
411 -- END old stuff
412 #endif
413 \end{code}
414
415
416 %************************************************************************
417 %*                                                                      *
418 \subsection{Initial persistent state}
419 %*                                                                      *
420 %************************************************************************
421
422 \begin{code}
423 initPersistentCompilerState :: IO PersistentCompilerState
424 initPersistentCompilerState 
425 <<<<<<< HscMain.lhs
426   = do prs <- initPersistentRenamerState
427        return (
428         PCS { pcs_PST   = initPackageDetails,
429               pcs_insts = emptyInstEnv,
430               pcs_rules = emptyRuleEnv,
431               pcs_PRS   = initPersistentRenamerState 
432             }
433         )
434 =======
435   = PCS { pcs_PST   = initPackageDetails,
436           pcs_insts = emptyInstEnv,
437           pcs_rules = initRules,
438           pcs_PRS   = initPersistentRenamerState }
439 >>>>>>> 1.12
440
441 initPackageDetails :: PackageSymbolTable
442 initPackageDetails = extendTypeEnv emptyModuleEnv wiredInThings
443
444 initPersistentRenamerState :: IO PersistentRenamerState
445   = do ns <- mkSplitUniqSupply 'r'
446        return (
447         PRS { prsOrig  = Orig { origNames  = initOrigNames,
448                                origIParam = emptyFM },
449               prsDecls = emptyNameEnv,
450               prsInsts = emptyBag,
451               prsRules = emptyBag,
452               prsNS    = ns
453             }
454         )
455
456 initOrigNames :: FiniteMap (ModuleName,OccName) Name
457 initOrigNames = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
458               where
459                 grab names   = foldl add emptyFM names
460                 add env name = addToFM env (moduleName (nameModule name), nameOccName name) name
461
462
463 initRules :: RuleEnv
464 initRules = foldl add emptyVarEnv builtinRules
465           where
466             add env (name,rule) = extendNameEnv_C add1 env name [rule]
467             add1 rules _        = rule : rules
468 \end{code}
469
470
471
472 \begin{code}
473 writeIface this_mod old_iface new_iface
474            local_tycons local_classes inst_info
475            final_ids tidy_binds tidy_orphan_rules
476   = 
477     if isNothing opt_HiDir && isNothing opt_HiFile
478         then return ()  -- not producing any .hi file
479         else 
480
481     let 
482         hi_suf = case opt_HiSuf of { Nothing -> "hi"; Just suf -> suf }
483         filename = case opt_HiFile of {
484                         Just f  -> f;
485                         Nothing -> 
486                    case opt_HiDir of {
487                         Just dir -> dir ++ '/':moduleUserString this_mod 
488                                         ++ '.':hi_suf;
489                         Nothing  -> panic "writeIface"
490                 }}
491     in
492
493     do maybe_final_iface <- checkIface old_iface full_new_iface         
494        case maybe_final_iface of {
495           Nothing -> when opt_D_dump_rn_trace $
496                      putStrLn "Interface file unchanged" ;  -- No need to update .hi file
497
498           Just final_iface ->
499
500        do  let mod_vers_unchanged = case old_iface of
501                                       Just iface -> pi_vers iface == pi_vers final_iface
502                                       Nothing -> False
503            when (mod_vers_unchanged && opt_D_dump_rn_trace) $
504                 putStrLn "Module version unchanged, but usages differ; hence need new hi file"
505
506            if_hdl <- openFile filename WriteMode
507            printForIface if_hdl (pprIface final_iface)
508            hClose if_hdl
509     }   
510   where
511     full_new_iface = completeIface new_iface local_tycons local_classes
512                                              inst_info final_ids tidy_binds
513                                              tidy_orphan_rules
514 \end{code}
515
516
517 %************************************************************************
518 %*                                                                      *
519 \subsection{Printing the interface}
520 %*                                                                      *
521 %************************************************************************
522
523 \begin{code}
524 pprIface (ParsedIface { pi_mod = mod, pi_vers = mod_vers, pi_orphan = orphan,
525                         pi_usages = usages, pi_exports = exports, 
526                         pi_fixity = (fix_vers, fixities),
527                         pi_insts = insts, pi_decls = decls, 
528                         pi_rules = (rule_vers, rules), pi_deprecs = deprecs })
529  = vcat [ ptext SLIT("__interface")
530                 <+> doubleQuotes (ptext opt_InPackage)
531                 <+> ppr mod <+> ppr mod_vers <+> pp_sub_vers
532                 <+> (if orphan then char '!' else empty)
533                 <+> int opt_HiVersion
534                 <+> ptext SLIT("where")
535         , vcat (map pprExport exports)
536         , vcat (map pprUsage usages)
537         , pprFixities fixities
538         , vcat [ppr i <+> semi | i <- insts]
539         , vcat [ppr_vers v <+> ppr d <> semi | (v,d) <- decls]
540         , pprRules rules
541         , pprDeprecs deprecs
542         ]
543   where
544     ppr_vers v | v == initialVersion = empty
545                | otherwise           = int v
546     pp_sub_vers 
547         | fix_vers == initialVersion && rule_vers == initialVersion = empty
548         | otherwise = brackets (ppr fix_vers <+> ppr rule_vers)
549 \end{code}
550
551 When printing export lists, we print like this:
552         Avail   f               f
553         AvailTC C [C, x, y]     C(x,y)
554         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
555
556 \begin{code}
557 pprExport :: ExportItem -> SDoc
558 pprExport (mod, items)
559  = hsep [ ptext SLIT("__export "), ppr mod, hsep (map upp_avail items) ] <> semi
560   where
561     upp_avail :: RdrAvailInfo -> SDoc
562     upp_avail (Avail name)      = pprOccName name
563     upp_avail (AvailTC name []) = empty
564     upp_avail (AvailTC name ns) = hcat [pprOccName name, bang, upp_export ns']
565                                 where
566                                   bang | name `elem` ns = empty
567                                        | otherwise      = char '|'
568                                   ns' = filter (/= name) ns
569     
570     upp_export []    = empty
571     upp_export names = braces (hsep (map pprOccName names))
572 \end{code}
573
574
575 \begin{code}
576 pprUsage :: ImportVersion OccName -> SDoc
577 pprUsage (m, has_orphans, is_boot, whats_imported)
578   = hsep [ptext SLIT("import"), pprModuleName m, 
579           pp_orphan, pp_boot,
580           upp_import_versions whats_imported
581     ] <> semi
582   where
583     pp_orphan | has_orphans = char '!'
584               | otherwise   = empty
585     pp_boot   | is_boot     = char '@'
586               | otherwise   = empty
587
588         -- Importing the whole module is indicated by an empty list
589     upp_import_versions NothingAtAll   = empty
590     upp_import_versions (Everything v) = dcolon <+> int v
591     upp_import_versions (Specifically vm vf vr nvs)
592       = dcolon <+> int vm <+> int vf <+> int vr <+> hsep [ ppr n <+> int v | (n,v) <- nvs ]
593 \end{code}
594
595
596 \begin{code}
597 pprFixities []    = empty
598 pprFixities fixes = hsep (map ppr fixes) <> semi
599
600 pprRules []    = empty
601 pprRules rules = hsep [ptext SLIT("{-## __R"), hsep (map ppr rules), ptext SLIT("##-}")]
602
603 pprDeprecs []   = empty
604 pprDeprecs deps = hsep [ ptext SLIT("{-## __D"), guts, ptext SLIT("##-}")]
605                 where
606                   guts = hsep [ ppr ie <+> doubleQuotes (ppr txt) <> semi 
607                               | Deprecation ie txt _ <- deps ]
608 \end{code}
609
610