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