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