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