[project @ 1997-07-27 01:27:06 by sof]
[ghc-hetmet.git] / ghc / compiler / main / Main.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1996
3 %
4 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module Main ( main ) where
10
11 IMP_Ubiq(){-uitous-}
12 IMPORT_1_3(IO(hGetContents,stdin,stderr,hPutStr,hClose,openFile,IOMode(..)))
13
14 import HsSyn
15 import RdrHsSyn         ( RdrName )
16 import BasicTypes       ( NewOrData(..) )
17
18 import ReadPrefix       ( rdModule )
19 import Rename           ( renameModule )
20 import RnMonad          ( ExportEnv )
21
22 import MkIface          -- several functions
23 import TcModule         ( typecheckModule )
24 import Desugar          ( deSugar, pprDsWarnings
25 #if __GLASGOW_HASKELL__ <= 200
26                           , DsMatchContext, DsWarnFlavour 
27 #endif
28                         )
29 import SimplCore        ( core2core )
30 import CoreToStg        ( topCoreBindsToStg )
31 import StgSyn           ( collectFinalStgBinders )
32 import SimplStg         ( stg2stg )
33 import CodeGen          ( codeGen )
34 #if ! OMIT_NATIVE_CODEGEN
35 import AsmCodeGen       ( dumpRealAsm, writeRealAsm )
36 #endif
37
38 import AbsCSyn          ( absCNop, AbstractC )
39 import AbsCUtils        ( flattenAbsC )
40 import CoreUnfold       ( Unfolding )
41 import Bag              ( emptyBag, isEmptyBag )
42 import CmdLineOpts
43 import ErrUtils         ( pprBagOfErrors, ghcExit )
44 import Maybes           ( maybeToBool, MaybeErr(..) )
45 import Specialise       ( SpecialiseData(..) )
46 import StgSyn           ( pprPlainStgBinding, GenStgBinding )
47 import TcInstUtil       ( InstInfo )
48 import TyCon            ( isDataTyCon )
49 import UniqSupply       ( mkSplitUniqSupply )
50
51 import PprAbsC          ( dumpRealC, writeRealC )
52 import PprCore          ( pprCoreBinding )
53 import Outputable       ( PprStyle(..), Outputable(..) )
54 import Pretty
55
56 import Id               ( GenId )               -- instances
57 import Name             ( Name )                -- instances
58 import PprType          ( GenType, GenTyVar )   -- instances
59 import TyVar            ( GenTyVar )            -- instances
60 import Unique           ( Unique )              -- instances
61 \end{code}
62
63 \begin{code}
64 main =
65  _scc_ "main" 
66  hGetContents stdin     >>= \ input_pgm ->
67  let
68     cmd_line_info = classifyOpts
69  in
70  doIt cmd_line_info input_pgm
71 \end{code}
72
73 \begin{code}
74 doIt :: ([CoreToDo], [StgToDo]) -> String -> IO ()
75
76 doIt (core_cmds, stg_cmds) input_pgm
77   = doDump opt_Verbose ("Glasgow Haskell Compiler, version " ++ show PROJECTVERSION ++ ", for Haskell 1.4") "" >>
78     -- ******* READER
79     show_pass "Reader"  >>
80     _scc_     "Reader"
81     rdModule            >>= \ (mod_name, rdr_module) ->
82
83     doDump opt_D_dump_rdr "Reader:"
84         (pp_show (ppr pprStyle rdr_module))     >>
85
86     doDump opt_D_source_stats "\nSource Statistics:"
87         (pp_show (ppSourceStats rdr_module))    >>
88
89     -- UniqueSupplies for later use (these are the only lower case uniques)
90 --    _scc_     "spl-rn"
91     mkSplitUniqSupply 'r'       >>= \ rn_uniqs  -> -- renamer
92 --    _scc_     "spl-tc"
93     mkSplitUniqSupply 'a'       >>= \ tc_uniqs  -> -- typechecker
94 --    _scc_     "spl-ds"
95     mkSplitUniqSupply 'd'       >>= \ ds_uniqs  -> -- desugarer
96 --    _scc_     "spl-sm"
97     mkSplitUniqSupply 's'       >>= \ sm_uniqs  -> -- core-to-core simplifier
98 --    _scc_     "spl-c2s"
99     mkSplitUniqSupply 'c'       >>= \ c2s_uniqs -> -- core-to-stg
100 --    _scc_     "spl-st"
101     mkSplitUniqSupply 'g'       >>= \ st_uniqs  -> -- stg-to-stg passes
102 --    _scc_     "spl-absc"
103     mkSplitUniqSupply 'f'       >>= \ fl_uniqs  -> -- absC flattener
104 --    _scc_     "spl-ncg"
105     mkSplitUniqSupply 'n'       >>= \ ncg_uniqs -> -- native-code generator
106
107     -- ******* RENAMER
108     show_pass "Renamer"                         >>
109     _scc_     "Renamer"
110
111     renameModule rn_uniqs rdr_module >>=
112         \ (maybe_rn_stuff, rn_errs_bag, rn_warns_bag) ->
113
114     checkErrors rn_errs_bag rn_warns_bag        >>
115     case maybe_rn_stuff of {
116         Nothing ->      -- Hurrah!  Renamer reckons that there's no need to
117                         -- go any further
118                         ghcExit 0 ;
119
120                 -- Oh well, we've got to recompile for real
121         Just (rn_mod, iface_file_stuff, rn_name_supply, imported_modules) ->
122
123
124
125     doDump opt_D_dump_rn "Renamer:"
126         (pp_show (ppr pprStyle rn_mod))         >>
127
128     -- Safely past renaming: we can start the interface file:
129     -- (the iface file is produced incrementally, as we have
130     -- the information that we need...; we use "iface<blah>")
131     -- "endIface" finishes the job.
132     startIface mod_name                                 >>= \ if_handle ->
133     ifaceMain if_handle iface_file_stuff                >>
134
135
136     -- ******* TYPECHECKER
137     show_pass "TypeCheck"                       >>
138     _scc_     "TypeCheck"
139     case (case (typecheckModule tc_uniqs {-idinfo_fm-} rn_name_supply rn_mod) of
140             Succeeded (stuff, warns)
141                 -> (emptyBag, warns, stuff)
142             Failed (errs, warns)
143                 -> (errs, warns, error "tc_results"))
144
145     of { (tc_errs_bag, tc_warns_bag, tc_results) ->
146
147     checkErrors tc_errs_bag tc_warns_bag        >>
148
149     case tc_results
150     of {  (all_binds,
151            local_tycons, local_classes, inst_info, pragma_tycon_specs,
152            ddump_deriv) ->
153
154     doDump opt_D_dump_tc "Typechecked:"
155         (pp_show (ppr pprStyle all_binds))      >>
156
157     doDump opt_D_dump_deriv "Derived instances:"
158         (pp_show (ddump_deriv pprStyle))        >>
159
160     -- ******* DESUGARER
161     show_pass "DeSugar"                         >>
162     _scc_     "DeSugar"
163     let
164         (desugared,ds_warnings)
165           = deSugar ds_uniqs mod_name all_binds
166     in
167     (if isEmptyBag ds_warnings then
168         return ()
169      else
170         hPutStr stderr (pp_show (pprDsWarnings pprErrorsStyle ds_warnings))
171         >> hPutStr stderr "\n"
172     )                                           >>
173
174     doDump opt_D_dump_ds "Desugared:" (pp_show (vcat
175         (map (pprCoreBinding pprStyle) desugared)))
176                                                 >>
177
178     -- ******* CORE-TO-CORE SIMPLIFICATION (NB: I/O op)
179     show_pass "Core2Core"                       >>
180     _scc_     "Core2Core"
181     let
182         local_data_tycons = filter isDataTyCon local_tycons
183     in
184     core2core core_cmds mod_name pprStyle
185               sm_uniqs local_data_tycons pragma_tycon_specs desugared
186                                                 >>=
187
188          \ (simplified,
189             SpecData _ _ _ gen_data_tycons all_tycon_specs _ _ _) ->
190
191     doDump opt_D_dump_simpl "Simplified:" (pp_show (vcat
192         (map (pprCoreBinding pprStyle) simplified)))
193                                                 >>
194
195     -- ******* STG-TO-STG SIMPLIFICATION
196     show_pass "Core2Stg"                        >>
197     _scc_     "Core2Stg"
198     let
199         stg_binds   = topCoreBindsToStg c2s_uniqs simplified
200     in
201
202     show_pass "Stg2Stg"                         >>
203     _scc_     "Stg2Stg"
204     stg2stg stg_cmds mod_name pprStyle st_uniqs stg_binds
205                                                 >>=
206
207         \ (stg_binds2, cost_centre_info) ->
208
209     doDump opt_D_dump_stg "STG syntax:"
210         (pp_show (vcat (map (pprPlainStgBinding pprStyle) stg_binds2)))
211                                                 >>
212
213         -- Dump instance decls and type signatures into the interface file
214     let
215         final_ids = collectFinalStgBinders stg_binds2
216     in
217     _scc_     "Interface"
218     ifaceDecls if_handle local_tycons local_classes inst_info final_ids simplified      >>
219     endIface if_handle                                          >>
220     -- We are definitely done w/ interface-file stuff at this point:
221     -- (See comments near call to "startIface".)
222     
223
224     -- ******* "ABSTRACT", THEN "FLAT", THEN *REAL* C!
225     show_pass "CodeGen"                         >>
226     _scc_     "CodeGen"
227     let
228         abstractC      = codeGen mod_name               -- module name for CC labelling
229                                  cost_centre_info
230                                  imported_modules       -- import names for CC registering
231                                  gen_data_tycons        -- type constructors generated locally
232                                  all_tycon_specs        -- tycon specialisations
233                                  stg_binds2
234
235         flat_abstractC = flattenAbsC fl_uniqs abstractC
236     in
237     doDump opt_D_dump_absC  "Abstract C:"
238         (dumpRealC abstractC)                   >>
239
240     doDump opt_D_dump_flatC "Flat Abstract C:"
241         (dumpRealC flat_abstractC)              >>
242
243     show_pass "CodeOutput"                      >>
244     _scc_     "CodeOutput"
245     -- You can have C (c_output) or assembly-language (ncg_output),
246     -- but not both.  [Allowing for both gives a space leak on
247     -- flat_abstractC.  WDP 94/10]
248     let
249         (flat_absC_c, flat_absC_ncg) =
250            case (maybeToBool opt_ProduceC || opt_D_dump_realC,
251                  maybeToBool opt_ProduceS || opt_D_dump_asm) of
252              (True,  False) -> (flat_abstractC, absCNop)
253              (False, True)  -> (absCNop, flat_abstractC)
254              (False, False) -> (absCNop, absCNop)
255              (True,  True)  -> error "ERROR: Can't do both .hc and .s at the same time"
256
257         c_output_d = dumpRealC flat_absC_c
258         c_output_w = (\ f -> writeRealC f flat_absC_c)
259
260 #if OMIT_NATIVE_CODEGEN
261         ncg_output_d = error "*** GHC not built with a native-code generator ***"
262         ncg_output_w = ncg_output_d
263 #else
264         ncg_output_d = dumpRealAsm flat_absC_ncg ncg_uniqs
265         ncg_output_w = (\ f -> writeRealAsm f flat_absC_ncg ncg_uniqs)
266 #endif
267     in
268
269     doDump opt_D_dump_asm "" ncg_output_d       >>
270     doOutput opt_ProduceS ncg_output_w          >>
271
272     doDump opt_D_dump_realC "" c_output_d       >>
273     doOutput opt_ProduceC c_output_w            >>
274
275     ghcExit 0
276     } } }
277   where
278     -------------------------------------------------------------
279     -- ****** printing styles and column width:
280
281
282     -------------------------------------------------------------
283     -- ****** help functions:
284
285     show_pass
286       = if opt_D_show_passes
287         then \ what -> hPutStr stderr ("*** "++what++":\n")
288         else \ what -> return ()
289
290     doOutput switch io_action
291       = case switch of
292           Nothing -> return ()
293           Just fname ->
294             openFile fname WriteMode    >>= \ handle ->
295             io_action handle            >>
296             hClose handle
297
298     doDump switch hdr string
299       = if switch
300         then hPutStr stderr ("\n\n" ++ (take 80 $ repeat '=')) >>
301              hPutStr stderr ('\n': hdr)     >>
302              hPutStr stderr ('\n': string)  >>
303              hPutStr stderr "\n"
304         else return ()
305
306
307 pprCols = (80 :: Int) -- could make configurable
308
309 (pprStyle, pprErrorsStyle)
310   | opt_PprStyle_All   = (PprShowAll, PprShowAll)
311   | opt_PprStyle_Debug = (PprDebug,   PprDebug)
312   | opt_PprStyle_User  = (PprQuote,   PprQuote)
313   | otherwise          = (PprDebug,   PprQuote)
314
315 pp_show p = show p      -- ToDo: use pprCols
316
317 checkErrors errs_bag warns_bag
318   | not (isEmptyBag errs_bag)
319   =     hPutStr stderr (pp_show (pprBagOfErrors pprErrorsStyle errs_bag))
320         >> hPutStr stderr "\n" >>
321         hPutStr stderr (pp_show (pprBagOfErrors pprErrorsStyle warns_bag))
322         >> hPutStr stderr "\n" >>
323         ghcExit 1
324
325   | not (isEmptyBag warns_bag)
326   = hPutStr stderr (pp_show (pprBagOfErrors pprErrorsStyle warns_bag))  >> 
327     hPutStr stderr "\n"
328  
329   | otherwise = return ()
330
331
332 ppSourceStats (HsModule name version exports imports fixities decls src_loc)
333  = vcat (map pp_val
334                [("ExportAll        ", export_all), -- 1 if no export list
335                 ("ExportDecls      ", export_ds),
336                 ("ExportModules    ", export_ms),
337                 ("Imports          ", import_no),
338                 ("  ImpQual        ", import_qual),
339                 ("  ImpAs          ", import_as),
340                 ("  ImpAll         ", import_all),
341                 ("  ImpPartial     ", import_partial),
342                 ("  ImpHiding      ", import_hiding),
343                 ("FixityDecls      ", fixity_ds),
344                 ("DefaultDecls     ", default_ds),
345                 ("TypeDecls        ", type_ds),
346                 ("DataDecls        ", data_ds),
347                 ("NewTypeDecls     ", newt_ds),
348                 ("DataConstrs      ", data_constrs),
349                 ("DataDerivings    ", data_derivs),
350                 ("ClassDecls       ", class_ds),
351                 ("ClassMethods     ", class_method_ds),
352                 ("DefaultMethods   ", default_method_ds),
353                 ("InstDecls        ", inst_ds),
354                 ("InstMethods      ", inst_method_ds),
355                 ("TypeSigs         ", bind_tys),
356                 ("ValBinds         ", val_bind_ds),
357                 ("FunBinds         ", fn_bind_ds),
358                 ("InlineMeths      ", method_inlines),
359                 ("InlineBinds      ", bind_inlines),
360 --              ("SpecialisedData  ", data_specs),
361 --              ("SpecialisedInsts ", inst_specs),
362                 ("SpecialisedMeths ", method_specs),
363                 ("SpecialisedBinds ", bind_specs)
364                ])
365   where
366     pp_val (str, 0) = empty
367     pp_val (str, n) = hcat [text str, int n]
368
369     fixity_ds   = length fixities
370     type_decls  = [d | TyD d@(TySynonym _ _ _ _)    <- decls]
371     data_decls  = [d | TyD d@(TyData DataType _ _ _ _ _ _ _) <- decls]
372     newt_decls  = [d | TyD d@(TyData NewType  _ _ _ _ _ _ _) <- decls]
373     type_ds     = length type_decls
374     data_ds     = length data_decls
375     newt_ds     = length newt_decls
376     class_decls = [d | ClD d <- decls]
377     class_ds    = length class_decls
378     inst_decls  = [d | InstD d <- decls]
379     inst_ds     = length inst_decls
380     default_ds  = length [() | DefD _ <- decls]
381     val_decls   = [d | ValD d <- decls]
382
383     real_exports = case exports of { Nothing -> []; Just es -> es }
384     n_exports    = length real_exports
385     export_ms    = length [() | IEModuleContents _ <- real_exports]
386     export_ds    = n_exports - export_ms
387     export_all   = case exports of { Nothing -> 1; other -> 0 }
388
389     (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
390         = count_binds (foldr ThenBinds EmptyBinds val_decls)
391
392     (import_no, import_qual, import_as, import_all, import_partial, import_hiding)
393         = foldr add6 (0,0,0,0,0,0) (map import_info imports)
394     (data_constrs, data_derivs)
395         = foldr add2 (0,0) (map data_info (newt_decls ++ data_decls))
396     (class_method_ds, default_method_ds)
397         = foldr add2 (0,0) (map class_info class_decls)
398     (inst_method_ds, method_specs, method_inlines)
399         = foldr add3 (0,0,0) (map inst_info inst_decls)
400
401
402     count_binds EmptyBinds        = (0,0,0,0,0)
403     count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
404     count_binds (MonoBind b sigs _) = case (count_monobinds b, count_sigs sigs) of
405                                         ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
406
407     count_monobinds EmptyMonoBinds        = (0,0)
408     count_monobinds (AndMonoBinds b1 b2)  = count_monobinds b1 `add2` count_monobinds b2
409     count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
410     count_monobinds (PatMonoBind p r _)   = (0,1)
411     count_monobinds (FunMonoBind f _ m _) = (0,1)
412
413     count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
414
415     sig_info (Sig _ _ _)          = (1,0,0,0)
416     sig_info (ClassOpSig _ _ _ _) = (0,1,0,0)
417     sig_info (SpecSig _ _ _ _)    = (0,0,1,0)
418     sig_info (InlineSig _ _)      = (0,0,0,1)
419     sig_info _                    = (0,0,0,0)
420
421     import_info (ImportDecl _ qual _ as spec _)
422         = add6 (1, qual_info qual, as_info as, 0,0,0) (spec_info spec)
423     qual_info False  = 0
424     qual_info True   = 1
425     as_info Nothing  = 0
426     as_info (Just _) = 1
427     spec_info Nothing           = (0,0,0,1,0,0)
428     spec_info (Just (False, _)) = (0,0,0,0,1,0)
429     spec_info (Just (True, _))  = (0,0,0,0,0,1)
430
431     data_info (TyData _ _ _ _ constrs derivs _ _)
432         = (length constrs, case derivs of {Nothing -> 0; Just ds -> length ds})
433
434     class_info (ClassDecl _ _ _ meth_sigs def_meths _ _)
435         = case count_sigs meth_sigs of
436             (_,classops,_,_) ->
437                (classops, addpr (count_monobinds def_meths))
438
439     inst_info (InstDecl _ inst_meths inst_sigs _ _)
440         = case count_sigs inst_sigs of
441             (_,_,ss,is) ->
442                (addpr (count_monobinds inst_meths), ss, is)
443
444     addpr (x,y) = x+y
445     add1 x1 y1  = x1+y1
446     add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
447     add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
448     add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
449     add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
450     add6 (x1,x2,x3,x4,x5,x6) (y1,y2,y3,y4,y5,y6) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5,x6+y6)
451 \end{code}