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