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