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