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