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