b96f1a2e1da74ded3c3bc8e065e5c3142cff2e01
[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, rn_env, 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     case (case (typecheckModule tc_uniqs {-idinfo_fm-} rn_env rn_mod) of
141             Succeeded (stuff, warns)
142                 -> (emptyBag, warns, stuff)
143             Failed (errs, warns)
144                 -> (errs, warns, error "tc_results"))
145
146     of { (tc_errs_bag, tc_warns_bag, tc_results) ->
147
148     if (not (isEmptyBag tc_errs_bag)) then
149         writeMn stderr (ppShow pprCols (pprBagOfErrors pprErrorsStyle tc_errs_bag))
150         `thenMn_` writeMn stderr "\n" `thenMn_`
151         writeMn stderr (ppShow pprCols (pprBagOfErrors pprErrorsStyle tc_warns_bag))
152         `thenMn_` writeMn stderr "\n" `thenMn_`
153         exitMn 1
154
155     else ( -- No typechecking errors ...
156
157     (if (isEmptyBag tc_warns_bag) then
158         returnMn ()
159      else
160         writeMn stderr (ppShow pprCols (pprBagOfErrors pprErrorsStyle tc_warns_bag))
161         `thenMn_` writeMn stderr "\n"
162     )                                           `thenMn_`
163
164     case tc_results
165     of {  (typechecked_quint@(recsel_binds, class_binds, inst_binds, val_binds, const_binds),
166            interface_stuff@(_,_,_,_,_),  -- @-pat just for strictness...
167            (local_tycons,local_classes), pragma_tycon_specs, ddump_deriv) ->
168
169     doDump opt_D_dump_tc "Typechecked:"
170         (pp_show (ppAboves [
171             ppr pprStyle recsel_binds,
172             ppr pprStyle class_binds,
173             ppr pprStyle inst_binds,
174             ppAboves (map (\ (i,e) -> ppr pprStyle (VarMonoBind i e)) const_binds),
175             ppr pprStyle val_binds]))           `thenMn_`
176
177     doDump opt_D_dump_deriv "Derived instances:"
178         (pp_show (ddump_deriv pprStyle))        `thenMn_`
179
180     -- ******* DESUGARER
181     show_pass "DeSugar"                         `thenMn_`
182     let
183         (desugared,ds_warnings)
184           = deSugar ds_uniqs ds_mod_name typechecked_quint
185     in
186     (if isEmptyBag ds_warnings then
187         returnMn ()
188      else
189         writeMn stderr (ppShow pprCols (pprDsWarnings pprErrorsStyle ds_warnings))
190         `thenMn_` writeMn stderr "\n"
191     )                                           `thenMn_`
192
193     doDump opt_D_dump_ds "Desugared:" (pp_show (ppAboves
194         (map (pprCoreBinding pprStyle) desugared)))
195                                                 `thenMn_`
196
197     -- ******* CORE-TO-CORE SIMPLIFICATION (NB: I/O op)
198     core2core core_cmds co_mod_name pprStyle
199               sm_uniqs local_tycons pragma_tycon_specs desugared
200                                                 `thenMn`
201
202          \ (simplified, inlinings_env,
203             SpecData _ _ _ gen_tycons all_tycon_specs _ _ _) ->
204
205     doDump opt_D_dump_simpl "Simplified:" (pp_show (ppAboves
206         (map (pprCoreBinding pprStyle) simplified)))
207                                                 `thenMn_`
208
209     -- ******* STG-TO-STG SIMPLIFICATION
210     show_pass "Core2Stg"                        `thenMn_`
211     let
212         stg_binds   = topCoreBindsToStg c2s_uniqs simplified
213     in
214
215     show_pass "Stg2Stg"                         `thenMn_`
216     stg2stg stg_cmds st_mod_name pprStyle st_uniqs stg_binds
217                                                 `thenMn`
218
219         \ (stg_binds2, cost_centre_info) ->
220
221     doDump opt_D_dump_stg "STG syntax:"
222         (pp_show (ppAboves (map (pprPlainStgBinding pprStyle) stg_binds2)))
223                                                 `thenMn_`
224
225 {- LATER ...
226     -- ******* INTERFACE GENERATION (needs STG output)
227 {-  let
228         mod_name = "_TestName_"
229         export_list_fns = (\ x -> False, \ x -> False)
230         inlinings_env = nullIdEnv
231         fixities = []
232         if_global_ids = []
233         if_ce = nullCE
234         if_tce = nullTCE
235         if_inst_info = emptyBag
236     in
237 -}
238
239     show_pass "Interface"                       `thenMn_`
240     let
241         mod_interface
242           = mkInterface if_mod_name export_list_fns
243                         inlinings_env all_tycon_specs
244                         interface_stuff
245                         stg_binds2
246     in
247     doOutput opt_ProduceHi ( \ file ->
248                          ppAppendFile file 1000{-pprCols-} mod_interface )
249                                                 `thenMn_`
250 -}
251
252     -- ******* "ABSTRACT", THEN "FLAT", THEN *REAL* C!
253     show_pass "CodeGen"                         `thenMn_`
254     let
255         abstractC      = codeGen cc_mod_name     -- module name for CC labelling
256                                  cost_centre_info
257                                  import_names -- import names for CC registering
258                                  gen_tycons      -- type constructors generated locally
259                                  all_tycon_specs -- tycon specialisations
260                                  stg_binds2
261
262         flat_abstractC = flattenAbsC fl_uniqs abstractC
263     in
264     doDump opt_D_dump_absC  "Abstract C:"
265         (dumpRealC abstractC)                   `thenMn_`
266
267     doDump opt_D_dump_flatC "Flat Abstract C:"
268         (dumpRealC flat_abstractC)              `thenMn_`
269
270     -- You can have C (c_output) or assembly-language (ncg_output),
271     -- but not both.  [Allowing for both gives a space leak on
272     -- flat_abstractC.  WDP 94/10]
273     let
274         (flat_absC_c, flat_absC_ncg) =
275            case (maybeToBool opt_ProduceC || opt_D_dump_realC,
276                  maybeToBool opt_ProduceS || opt_D_dump_asm) of
277              (True,  False) -> (flat_abstractC, absCNop)
278              (False, True)  -> (absCNop, flat_abstractC)
279              (False, False) -> (absCNop, absCNop)
280              (True,  True)  -> error "ERROR: Can't do both .hc and .s at the same time"
281
282         c_output_d = dumpRealC flat_absC_c
283         c_output_w = (\ f -> writeRealC f flat_absC_c)
284
285 #if OMIT_NATIVE_CODEGEN
286         ncg_output_d = error "*** GHC not built with a native-code generator ***"
287         ncg_output_w = ncg_output_d
288 #else
289         ncg_output_d = dumpRealAsm flat_absC_ncg ncg_uniqs
290         ncg_output_w = (\ f -> writeRealAsm f flat_absC_ncg ncg_uniqs)
291 #endif
292     in
293
294     doDump opt_D_dump_asm "" ncg_output_d       `thenMn_`
295     doOutput opt_ProduceS ncg_output_w          `thenMn_`
296
297     doDump opt_D_dump_realC "" c_output_d       `thenMn_`
298     doOutput opt_ProduceC c_output_w            `thenMn_`
299
300     exitMn 0
301     } ) }
302
303 {- LATER -}
304
305     }
306   where
307     -------------------------------------------------------------
308     -- ****** printing styles and column width:
309
310     pprCols = (80 :: Int) -- could make configurable
311
312     (pprStyle, pprErrorsStyle)
313       = if      opt_PprStyle_All   then
314                 (PprShowAll, PprShowAll)
315         else if opt_PprStyle_Debug then
316                 (PprDebug, PprDebug)
317         else if opt_PprStyle_User  then
318                 (PprForUser, PprForUser)
319         else -- defaults...
320                 (PprDebug, PprForUser)
321
322     pp_show p = ppShow {-WAS:pprCols-}10000{-random-} p
323
324     -------------------------------------------------------------
325     -- ****** help functions:
326
327     show_pass
328       = if opt_D_show_passes
329         then \ what -> writeMn stderr ("*** "++what++":\n")
330         else \ what -> returnMn ()
331
332     doOutput switch io_action
333       = case switch of
334           Nothing -> returnMn ()
335           Just fname ->
336             fopen fname "a+"    `thenPrimIO` \ file ->
337             if (file == ``NULL'') then
338                 error ("doOutput: failed to open:"++fname)
339             else
340                 io_action file          `thenMn`     \ () ->
341                 fclose file             `thenPrimIO` \ status ->
342                 if status == 0
343                 then returnMn ()
344                 else error ("doOutput: closed failed: "{-++show status++" "-}++fname)
345
346     doDump switch hdr string
347       = if switch
348         then writeMn stderr hdr             `thenMn_`
349              writeMn stderr ('\n': string)  `thenMn_`
350              writeMn stderr "\n"
351         else returnMn ()
352
353
354 ppSourceStats (HsModule name version exports imports fixities typedecls typesigs
355                       classdecls instdecls instsigs defdecls binds
356                       [{-no sigs-}] src_loc)
357  = ppAboves (map pp_val
358                [("ExportAll        ", export_all), -- 1 if no export list
359                 ("ExportDecls      ", export_ds),
360                 ("ExportModules    ", export_ms),
361                 ("Imports          ", import_no),
362                 ("  ImpQual        ", import_qual),
363                 ("  ImpAs          ", import_as),
364                 ("  ImpAll         ", import_all),
365                 ("  ImpPartial     ", import_partial),
366                 ("  ImpHiding      ", import_hiding),
367                 ("FixityDecls      ", fixity_ds),
368                 ("DefaultDecls     ", defalut_ds),
369                 ("TypeDecls        ", type_ds),
370                 ("DataDecls        ", data_ds),
371                 ("NewTypeDecls     ", newt_ds),
372                 ("DataConstrs      ", data_constrs),
373                 ("DataDerivings    ", data_derivs),
374                 ("ClassDecls       ", class_ds),
375                 ("ClassMethods     ", class_method_ds),
376                 ("DefaultMethods   ", default_method_ds),
377                 ("InstDecls        ", inst_ds),
378                 ("InstMethods      ", inst_method_ds),
379                 ("TypeSigs         ", bind_tys),
380                 ("ValBinds         ", val_bind_ds),
381                 ("FunBinds         ", fn_bind_ds),
382                 ("InlineMeths      ", method_inlines),
383                 ("InlineBinds      ", bind_inlines),
384                 ("SpecialisedData  ", data_specs),
385                 ("SpecialisedInsts ", inst_specs),
386                 ("SpecialisedMeths ", method_specs),
387                 ("SpecialisedBinds ", bind_specs)
388                ])
389   where
390     pp_val (str, 0) = ppNil
391     pp_val (str, n) = ppBesides [ppStr str, ppInt n]
392
393     (export_decls, export_mods) = getRawExportees exports
394     type_decls = filter is_type_decl typedecls
395     data_decls = filter is_data_decl typedecls
396     newt_decls = filter is_newt_decl typedecls
397
398     export_ds  = length export_decls
399     export_ms  = length export_mods
400     export_all = if export_ds == 0 && export_ms == 0 then 1 else 0
401
402     fixity_ds  = length fixities
403     defalut_ds = length defdecls
404     type_ds    = length type_decls
405     data_ds    = length data_decls
406     newt_ds    = length newt_decls
407     class_ds   = length classdecls
408     inst_ds    = length instdecls
409
410     (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
411         = count_binds binds
412
413     (import_no, import_qual, import_as, import_all, import_partial, import_hiding)
414         = foldr add6 (0,0,0,0,0,0) (map import_info imports)
415     (data_constrs, data_derivs)
416         = foldr add2 (0,0) (map data_info (newt_decls ++ data_decls))
417     (class_method_ds, default_method_ds)
418         = foldr add2 (0,0) (map class_info classdecls)
419     (inst_method_ds, method_specs, method_inlines)
420         = foldr add3 (0,0,0) (map inst_info instdecls)
421
422     data_specs  = length typesigs
423     inst_specs  = length instsigs
424
425     count_binds EmptyBinds        = (0,0,0,0,0)
426     count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
427     count_binds (SingleBind b)    = case count_bind b of
428                                       (vs,fs) -> (vs,fs,0,0,0)
429     count_binds (BindWith b sigs) = case (count_bind b, count_sigs sigs) of
430                                       ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
431
432     count_bind EmptyBind      = (0,0)
433     count_bind (NonRecBind b) = count_monobinds b
434     count_bind (RecBind b)    = count_monobinds b
435
436     count_monobinds EmptyMonoBinds        = (0,0)
437     count_monobinds (AndMonoBinds b1 b2)  = count_monobinds b1 `add2` count_monobinds b2
438     count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
439     count_monobinds (PatMonoBind p r _)   = (0,1)
440     count_monobinds (FunMonoBind f _ m _) = (0,1)
441
442     count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
443
444     sig_info (Sig _ _ _ _)        = (1,0,0,0)
445     sig_info (ClassOpSig _ _ _ _) = (0,1,0,0)
446     sig_info (SpecSig _ _ _ _)    = (0,0,1,0)
447     sig_info (InlineSig _ _)      = (0,0,0,1)
448     sig_info _                    = (0,0,0,0)
449
450     import_info (ImportDecl _ qual as spec _)
451         = add6 (1, qual_info qual, as_info as, 0,0,0) (spec_info spec)
452     qual_info False  = 0
453     qual_info True   = 1
454     as_info Nothing  = 0
455     as_info (Just _) = 1
456     spec_info Nothing           = (0,0,0,1,0,0)
457     spec_info (Just (False, _)) = (0,0,0,0,1,0)
458     spec_info (Just (True, _))  = (0,0,0,0,0,1)
459
460     data_info (TyData _ _ _ constrs derivs _ _)
461         = (length constrs, case derivs of {Nothing -> 0; Just ds -> length ds})
462     data_info (TyNew _ _ _ constr derivs _ _)
463         = (length constr, case derivs of {Nothing -> 0; Just ds -> length ds})
464
465     class_info (ClassDecl _ _ _ meth_sigs def_meths _ _)
466         = case count_sigs meth_sigs of
467             (_,classops,_,_) ->
468                (classops, addpr (count_monobinds def_meths))
469
470     inst_info (InstDecl _ _ inst_meths _ _ inst_sigs _ _)
471         = case count_sigs inst_sigs of
472             (_,_,ss,is) ->
473                (addpr (count_monobinds inst_meths), ss, is)
474
475     is_type_decl (TySynonym _ _ _ _)     = True
476     is_type_decl _                       = False
477     is_data_decl (TyData _ _ _ _ _ _ _)  = True
478     is_data_decl _                       = False
479     is_newt_decl (TyNew  _ _ _ _ _ _ _)  = True
480     is_newt_decl _                       = False
481
482     addpr (x,y) = x+y
483     add1 x1 y1  = x1+y1
484     add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
485     add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
486     add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
487     add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
488     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)
489 \end{code}