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