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