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