[project @ 1997-09-04 20:18:21 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, pprStgBindings )
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, doIfSet, dumpIfSet )
44 import Maybes           ( maybeToBool, MaybeErr(..) )
45 import Specialise       ( SpecialiseData(..) )
46 import StgSyn           ( 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 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
61 import Outputable       ( PprStyle(..), Outputable(..), pprDumpStyle, pprErrorsStyle )
62
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   = doIfSet opt_Verbose 
80         (hPutStr stderr ("Glasgow Haskell Compiler, version " ++ 
81                          show PROJECTVERSION ++ 
82                          ", for Haskell 1.4"))          >>
83
84     -- ******* READER
85     show_pass "Reader"  >>
86     _scc_     "Reader"
87     rdModule            >>= \ (mod_name, rdr_module) ->
88
89     dumpIfSet opt_D_dump_rdr "Reader"
90         (ppr pprDumpStyle rdr_module)           >>
91
92     dumpIfSet opt_D_source_stats "Source Statistics"
93         (ppSourceStats rdr_module)              >>
94
95     -- UniqueSupplies for later use (these are the only lower case uniques)
96 --    _scc_     "spl-rn"
97     mkSplitUniqSupply 'r'       >>= \ rn_uniqs  -> -- renamer
98 --    _scc_     "spl-tc"
99     mkSplitUniqSupply 'a'       >>= \ tc_uniqs  -> -- typechecker
100 --    _scc_     "spl-ds"
101     mkSplitUniqSupply 'd'       >>= \ ds_uniqs  -> -- desugarer
102 --    _scc_     "spl-sm"
103     mkSplitUniqSupply 's'       >>= \ sm_uniqs  -> -- core-to-core simplifier
104 --    _scc_     "spl-c2s"
105     mkSplitUniqSupply 'c'       >>= \ c2s_uniqs -> -- core-to-stg
106 --    _scc_     "spl-st"
107     mkSplitUniqSupply 'g'       >>= \ st_uniqs  -> -- stg-to-stg passes
108 --    _scc_     "spl-absc"
109     mkSplitUniqSupply 'f'       >>= \ fl_uniqs  -> -- absC flattener
110 --    _scc_     "spl-ncg"
111     mkSplitUniqSupply 'n'       >>= \ ncg_uniqs -> -- native-code generator
112
113     -- ******* RENAMER
114     show_pass "Renamer"                         >>
115     _scc_     "Renamer"
116
117     renameModule rn_uniqs rdr_module            >>=
118         \ maybe_rn_stuff ->
119     case maybe_rn_stuff of {
120         Nothing ->      -- Hurrah!  Renamer reckons that there's no need to
121                         -- go any further
122                         return ();
123         
124         Just (rn_mod, iface_file_stuff, rn_name_supply, imported_modules) ->
125                         -- Oh well, we've got to recompile for real
126
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     typecheckModule tc_uniqs rn_name_supply rn_mod      >>= \ maybe_tc_stuff ->
140     case maybe_tc_stuff of {
141         Nothing -> ghcExit 1;   -- Type checker failed
142
143         Just (all_binds,
144               local_tycons, local_classes, inst_info, pragma_tycon_specs,
145               ddump_deriv) ->
146
147
148     -- ******* DESUGARER
149     show_pass "DeSugar"                         >>
150     _scc_     "DeSugar"
151     deSugar ds_uniqs mod_name all_binds         >>= \ desugared ->
152
153
154     -- ******* CORE-TO-CORE SIMPLIFICATION
155     show_pass "Core2Core"                       >>
156     _scc_     "Core2Core"
157     let
158         local_data_tycons = filter isDataTyCon local_tycons
159     in
160     core2core core_cmds mod_name
161               sm_uniqs local_data_tycons pragma_tycon_specs desugared
162                                                 >>=
163          \ (simplified,
164             SpecData _ _ _ gen_data_tycons all_tycon_specs _ _ _) ->
165
166
167     -- ******* STG-TO-STG SIMPLIFICATION
168     show_pass "Core2Stg"                        >>
169     _scc_     "Core2Stg"
170     let
171         stg_binds   = topCoreBindsToStg c2s_uniqs simplified
172     in
173
174     show_pass "Stg2Stg"                         >>
175     _scc_     "Stg2Stg"
176     stg2stg stg_cmds mod_name st_uniqs stg_binds
177                                                 >>=
178         \ (stg_binds2, cost_centre_info) ->
179
180     dumpIfSet opt_D_dump_stg "STG syntax:"
181         (pprStgBindings pprDumpStyle stg_binds2)
182                                                 >>
183
184         -- Dump instance decls and type signatures into the interface file
185     let
186         final_ids = collectFinalStgBinders stg_binds2
187     in
188     _scc_     "Interface"
189     ifaceDecls if_handle local_tycons local_classes inst_info final_ids simplified      >>
190     endIface if_handle                                          >>
191     -- We are definitely done w/ interface-file stuff at this point:
192     -- (See comments near call to "startIface".)
193     
194
195     -- ******* "ABSTRACT", THEN "FLAT", THEN *REAL* C!
196     show_pass "CodeGen"                         >>
197     _scc_     "CodeGen"
198     let
199         abstractC      = codeGen mod_name               -- module name for CC labelling
200                                  cost_centre_info
201                                  imported_modules       -- import names for CC registering
202                                  gen_data_tycons        -- type constructors generated locally
203                                  all_tycon_specs        -- tycon specialisations
204                                  stg_binds2
205
206         flat_abstractC = flattenAbsC fl_uniqs abstractC
207     in
208     dumpIfSet opt_D_dump_absC "Abstract C"
209         (dumpRealC abstractC)                   >>
210
211     dumpIfSet opt_D_dump_flatC "Flat Abstract C"
212         (dumpRealC flat_abstractC)              >>
213
214     show_pass "CodeOutput"                      >>
215     _scc_     "CodeOutput"
216     -- You can have C (c_output) or assembly-language (ncg_output),
217     -- but not both.  [Allowing for both gives a space leak on
218     -- flat_abstractC.  WDP 94/10]
219     let
220         (flat_absC_c, flat_absC_ncg) =
221            case (maybeToBool opt_ProduceC || opt_D_dump_realC,
222                  maybeToBool opt_ProduceS || opt_D_dump_asm) of
223              (True,  False) -> (flat_abstractC, absCNop)
224              (False, True)  -> (absCNop, flat_abstractC)
225              (False, False) -> (absCNop, absCNop)
226              (True,  True)  -> error "ERROR: Can't do both .hc and .s at the same time"
227
228         c_output_d = dumpRealC flat_absC_c
229         c_output_w = (\ f -> writeRealC f flat_absC_c)
230
231 #if OMIT_NATIVE_CODEGEN
232         ncg_output_d = error "*** GHC not built with a native-code generator ***"
233         ncg_output_w = ncg_output_d
234 #else
235         ncg_output_d = dumpRealAsm flat_absC_ncg ncg_uniqs
236         ncg_output_w = (\ f -> writeRealAsm f flat_absC_ncg ncg_uniqs)
237 #endif
238     in
239
240     dumpIfSet opt_D_dump_asm "Asm code" ncg_output_d    >>
241     doOutput opt_ProduceS ncg_output_w                  >>
242
243     dumpIfSet opt_D_dump_realC "Real C" c_output_d      >>
244     doOutput opt_ProduceC c_output_w                    >>
245
246     ghcExit 0
247     } }
248   where
249     -------------------------------------------------------------
250     -- ****** help functions:
251
252     show_pass
253       = if opt_D_show_passes
254         then \ what -> hPutStr stderr ("*** "++what++":\n")
255         else \ what -> return ()
256
257     doOutput switch io_action
258       = case switch of
259           Nothing -> return ()
260           Just fname ->
261             openFile fname WriteMode    >>= \ handle ->
262             io_action handle            >>
263             hClose handle
264
265
266 ppSourceStats (HsModule name version exports imports fixities decls src_loc)
267  = vcat (map pp_val
268                [("ExportAll        ", export_all), -- 1 if no export list
269                 ("ExportDecls      ", export_ds),
270                 ("ExportModules    ", export_ms),
271                 ("Imports          ", import_no),
272                 ("  ImpQual        ", import_qual),
273                 ("  ImpAs          ", import_as),
274                 ("  ImpAll         ", import_all),
275                 ("  ImpPartial     ", import_partial),
276                 ("  ImpHiding      ", import_hiding),
277                 ("FixityDecls      ", fixity_ds),
278                 ("DefaultDecls     ", default_ds),
279                 ("TypeDecls        ", type_ds),
280                 ("DataDecls        ", data_ds),
281                 ("NewTypeDecls     ", newt_ds),
282                 ("DataConstrs      ", data_constrs),
283                 ("DataDerivings    ", data_derivs),
284                 ("ClassDecls       ", class_ds),
285                 ("ClassMethods     ", class_method_ds),
286                 ("DefaultMethods   ", default_method_ds),
287                 ("InstDecls        ", inst_ds),
288                 ("InstMethods      ", inst_method_ds),
289                 ("TypeSigs         ", bind_tys),
290                 ("ValBinds         ", val_bind_ds),
291                 ("FunBinds         ", fn_bind_ds),
292                 ("InlineMeths      ", method_inlines),
293                 ("InlineBinds      ", bind_inlines),
294 --              ("SpecialisedData  ", data_specs),
295 --              ("SpecialisedInsts ", inst_specs),
296                 ("SpecialisedMeths ", method_specs),
297                 ("SpecialisedBinds ", bind_specs)
298                ])
299   where
300     pp_val (str, 0) = empty
301     pp_val (str, n) = hcat [text str, int n]
302
303     fixity_ds   = length fixities
304     type_decls  = [d | TyD d@(TySynonym _ _ _ _)    <- decls]
305     data_decls  = [d | TyD d@(TyData DataType _ _ _ _ _ _ _) <- decls]
306     newt_decls  = [d | TyD d@(TyData NewType  _ _ _ _ _ _ _) <- decls]
307     type_ds     = length type_decls
308     data_ds     = length data_decls
309     newt_ds     = length newt_decls
310     class_decls = [d | ClD d <- decls]
311     class_ds    = length class_decls
312     inst_decls  = [d | InstD d <- decls]
313     inst_ds     = length inst_decls
314     default_ds  = length [() | DefD _ <- decls]
315     val_decls   = [d | ValD d <- decls]
316
317     real_exports = case exports of { Nothing -> []; Just es -> es }
318     n_exports    = length real_exports
319     export_ms    = length [() | IEModuleContents _ <- real_exports]
320     export_ds    = n_exports - export_ms
321     export_all   = case exports of { Nothing -> 1; other -> 0 }
322
323     (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
324         = count_binds (foldr ThenBinds EmptyBinds val_decls)
325
326     (import_no, import_qual, import_as, import_all, import_partial, import_hiding)
327         = foldr add6 (0,0,0,0,0,0) (map import_info imports)
328     (data_constrs, data_derivs)
329         = foldr add2 (0,0) (map data_info (newt_decls ++ data_decls))
330     (class_method_ds, default_method_ds)
331         = foldr add2 (0,0) (map class_info class_decls)
332     (inst_method_ds, method_specs, method_inlines)
333         = foldr add3 (0,0,0) (map inst_info inst_decls)
334
335
336     count_binds EmptyBinds        = (0,0,0,0,0)
337     count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
338     count_binds (MonoBind b sigs _) = case (count_monobinds b, count_sigs sigs) of
339                                         ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
340
341     count_monobinds EmptyMonoBinds        = (0,0)
342     count_monobinds (AndMonoBinds b1 b2)  = count_monobinds b1 `add2` count_monobinds b2
343     count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
344     count_monobinds (PatMonoBind p r _)   = (0,1)
345     count_monobinds (FunMonoBind f _ m _) = (0,1)
346
347     count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
348
349     sig_info (Sig _ _ _)          = (1,0,0,0)
350     sig_info (ClassOpSig _ _ _ _) = (0,1,0,0)
351     sig_info (SpecSig _ _ _ _)    = (0,0,1,0)
352     sig_info (InlineSig _ _)      = (0,0,0,1)
353     sig_info _                    = (0,0,0,0)
354
355     import_info (ImportDecl _ qual _ as spec _)
356         = add6 (1, qual_info qual, as_info as, 0,0,0) (spec_info spec)
357     qual_info False  = 0
358     qual_info True   = 1
359     as_info Nothing  = 0
360     as_info (Just _) = 1
361     spec_info Nothing           = (0,0,0,1,0,0)
362     spec_info (Just (False, _)) = (0,0,0,0,1,0)
363     spec_info (Just (True, _))  = (0,0,0,0,0,1)
364
365     data_info (TyData _ _ _ _ constrs derivs _ _)
366         = (length constrs, case derivs of {Nothing -> 0; Just ds -> length ds})
367
368     class_info (ClassDecl _ _ _ meth_sigs def_meths _ _)
369         = case count_sigs meth_sigs of
370             (_,classops,_,_) ->
371                (classops, addpr (count_monobinds def_meths))
372
373     inst_info (InstDecl _ inst_meths inst_sigs _ _)
374         = case count_sigs inst_sigs of
375             (_,_,ss,is) ->
376                (addpr (count_monobinds inst_meths), ss, is)
377
378     addpr (x,y) = x+y
379     add1 x1 y1  = x1+y1
380     add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
381     add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
382     add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
383     add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
384     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)
385 \end{code}