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