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