54a67834293fc99af61ead8ceab54918d3942f83
[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 Bag              ( emptyBag, isEmptyBag )
32 import CmdLineOpts
33 import ErrUtils         ( pprBagOfErrors, ghcExit )
34 import Maybes           ( maybeToBool, MaybeErr(..) )
35 import RdrHsSyn         ( getRawExportees )
36 import Specialise       ( SpecialiseData(..) )
37 import StgSyn           ( pprPlainStgBinding, GenStgBinding )
38 import TcInstUtil       ( InstInfo )
39 import TyCon            ( isDataTyCon )
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 2.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            export_stuff, 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 export_stuff rn_env >>
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@(_,local_tycons,_,_),
163            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     let
202         local_data_tycons = filter isDataTyCon local_tycons
203     in
204     core2core core_cmds mod_name pprStyle
205               sm_uniqs local_data_tycons pragma_tycon_specs desugared
206                                                 >>=
207
208          \ (simplified, inlinings_env,
209             SpecData _ _ _ gen_tycons all_tycon_specs _ _ _) ->
210
211     doDump opt_D_dump_simpl "Simplified:" (pp_show (ppAboves
212         (map (pprCoreBinding pprStyle) simplified)))
213                                                 >>
214
215     -- ******* STG-TO-STG SIMPLIFICATION
216     show_pass "Core2Stg"                        >>
217     _scc_     "Core2Stg"
218     let
219         stg_binds   = topCoreBindsToStg c2s_uniqs simplified
220     in
221
222     show_pass "Stg2Stg"                         >>
223     _scc_     "Stg2Stg"
224     stg2stg stg_cmds mod_name pprStyle st_uniqs stg_binds
225                                                 >>=
226
227         \ (stg_binds2, cost_centre_info) ->
228
229     doDump opt_D_dump_stg "STG syntax:"
230         (pp_show (ppAboves (map (pprPlainStgBinding pprStyle) stg_binds2)))
231                                                 >>
232
233     -- We are definitely done w/ interface-file stuff at this point:
234     -- (See comments near call to "startIface".)
235     endIface if_handle                          >>
236
237     -- ******* "ABSTRACT", THEN "FLAT", THEN *REAL* C!
238     show_pass "CodeGen"                         >>
239     _scc_     "CodeGen"
240     let
241         abstractC      = codeGen mod_name     -- module name for CC labelling
242                                  cost_centre_info
243                                  import_names -- import names for CC registering
244                                  gen_tycons      -- type constructors generated locally
245                                  all_tycon_specs -- tycon specialisations
246                                  stg_binds2
247
248         flat_abstractC = flattenAbsC fl_uniqs abstractC
249     in
250     doDump opt_D_dump_absC  "Abstract C:"
251         (dumpRealC abstractC)                   >>
252
253     doDump opt_D_dump_flatC "Flat Abstract C:"
254         (dumpRealC flat_abstractC)              >>
255
256     -- You can have C (c_output) or assembly-language (ncg_output),
257     -- but not both.  [Allowing for both gives a space leak on
258     -- flat_abstractC.  WDP 94/10]
259     let
260         (flat_absC_c, flat_absC_ncg) =
261            case (maybeToBool opt_ProduceC || opt_D_dump_realC,
262                  maybeToBool opt_ProduceS || opt_D_dump_asm) of
263              (True,  False) -> (flat_abstractC, absCNop)
264              (False, True)  -> (absCNop, flat_abstractC)
265              (False, False) -> (absCNop, absCNop)
266              (True,  True)  -> error "ERROR: Can't do both .hc and .s at the same time"
267
268         c_output_d = dumpRealC flat_absC_c
269         c_output_w = (\ f -> writeRealC f flat_absC_c)
270
271 #if OMIT_NATIVE_CODEGEN
272         ncg_output_d = error "*** GHC not built with a native-code generator ***"
273         ncg_output_w = ncg_output_d
274 #else
275         ncg_output_d = dumpRealAsm flat_absC_ncg ncg_uniqs
276         ncg_output_w = (\ f -> writeRealAsm f flat_absC_ncg ncg_uniqs)
277 #endif
278     in
279
280     doDump opt_D_dump_asm "" ncg_output_d       >>
281     doOutput opt_ProduceS ncg_output_w          >>
282
283     doDump opt_D_dump_realC "" c_output_d       >>
284     doOutput opt_ProduceC c_output_w            >>
285
286     ghcExit 0
287     } ) }
288   where
289     -------------------------------------------------------------
290     -- ****** printing styles and column width:
291
292     pprCols = (80 :: Int) -- could make configurable
293
294     (pprStyle, pprErrorsStyle)
295       = if      opt_PprStyle_All   then
296                 (PprShowAll, PprShowAll)
297         else if opt_PprStyle_Debug then
298                 (PprDebug, PprDebug)
299         else if opt_PprStyle_User  then
300                 (PprForUser, PprForUser)
301         else -- defaults...
302                 (PprDebug, PprForUser)
303
304     pp_show p = ppShow {-WAS:pprCols-}10000{-random-} p
305
306     -------------------------------------------------------------
307     -- ****** help functions:
308
309     show_pass
310       = if opt_D_show_passes
311         then \ what -> hPutStr stderr ("*** "++what++":\n")
312         else \ what -> return ()
313
314     doOutput switch io_action
315       = case switch of
316           Nothing -> return ()
317           Just fname ->
318             openFile fname WriteMode    >>= \ handle ->
319             io_action handle            >>
320             hClose handle
321
322     doDump switch hdr string
323       = if switch
324         then hPutStr stderr hdr             >>
325              hPutStr stderr ('\n': string)  >>
326              hPutStr stderr "\n"
327         else return ()
328
329
330 ppSourceStats (HsModule name version exports imports fixities typedecls typesigs
331                       classdecls instdecls instsigs defdecls binds
332                       [{-no sigs-}] src_loc)
333  = ppAboves (map pp_val
334                [("ExportAll        ", export_all), -- 1 if no export list
335                 ("ExportDecls      ", export_ds),
336                 ("ExportModules    ", export_ms),
337                 ("Imports          ", import_no),
338                 ("  ImpQual        ", import_qual),
339                 ("  ImpAs          ", import_as),
340                 ("  ImpAll         ", import_all),
341                 ("  ImpPartial     ", import_partial),
342                 ("  ImpHiding      ", import_hiding),
343                 ("FixityDecls      ", fixity_ds),
344                 ("DefaultDecls     ", defalut_ds),
345                 ("TypeDecls        ", type_ds),
346                 ("DataDecls        ", data_ds),
347                 ("NewTypeDecls     ", newt_ds),
348                 ("DataConstrs      ", data_constrs),
349                 ("DataDerivings    ", data_derivs),
350                 ("ClassDecls       ", class_ds),
351                 ("ClassMethods     ", class_method_ds),
352                 ("DefaultMethods   ", default_method_ds),
353                 ("InstDecls        ", inst_ds),
354                 ("InstMethods      ", inst_method_ds),
355                 ("TypeSigs         ", bind_tys),
356                 ("ValBinds         ", val_bind_ds),
357                 ("FunBinds         ", fn_bind_ds),
358                 ("InlineMeths      ", method_inlines),
359                 ("InlineBinds      ", bind_inlines),
360                 ("SpecialisedData  ", data_specs),
361                 ("SpecialisedInsts ", inst_specs),
362                 ("SpecialisedMeths ", method_specs),
363                 ("SpecialisedBinds ", bind_specs)
364                ])
365   where
366     pp_val (str, 0) = ppNil
367     pp_val (str, n) = ppBesides [ppStr str, ppInt n]
368
369     (export_decls, export_mods) = getRawExportees exports
370     type_decls = filter is_type_decl typedecls
371     data_decls = filter is_data_decl typedecls
372     newt_decls = filter is_newt_decl typedecls
373
374     export_ds  = length export_decls
375     export_ms  = length export_mods
376     export_all = if export_ds == 0 && export_ms == 0 then 1 else 0
377
378     fixity_ds  = length fixities
379     defalut_ds = length defdecls
380     type_ds    = length type_decls
381     data_ds    = length data_decls
382     newt_ds    = length newt_decls
383     class_ds   = length classdecls
384     inst_ds    = length instdecls
385
386     (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
387         = count_binds binds
388
389     (import_no, import_qual, import_as, import_all, import_partial, import_hiding)
390         = foldr add6 (0,0,0,0,0,0) (map import_info imports)
391     (data_constrs, data_derivs)
392         = foldr add2 (0,0) (map data_info (newt_decls ++ data_decls))
393     (class_method_ds, default_method_ds)
394         = foldr add2 (0,0) (map class_info classdecls)
395     (inst_method_ds, method_specs, method_inlines)
396         = foldr add3 (0,0,0) (map inst_info instdecls)
397
398     data_specs  = length typesigs
399     inst_specs  = length instsigs
400
401     count_binds EmptyBinds        = (0,0,0,0,0)
402     count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
403     count_binds (SingleBind b)    = case count_bind b of
404                                       (vs,fs) -> (vs,fs,0,0,0)
405     count_binds (BindWith b sigs) = case (count_bind b, count_sigs sigs) of
406                                       ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
407
408     count_bind EmptyBind      = (0,0)
409     count_bind (NonRecBind b) = count_monobinds b
410     count_bind (RecBind b)    = count_monobinds b
411
412     count_monobinds EmptyMonoBinds        = (0,0)
413     count_monobinds (AndMonoBinds b1 b2)  = count_monobinds b1 `add2` count_monobinds b2
414     count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
415     count_monobinds (PatMonoBind p r _)   = (0,1)
416     count_monobinds (FunMonoBind f _ m _) = (0,1)
417
418     count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
419
420     sig_info (Sig _ _ _ _)        = (1,0,0,0)
421     sig_info (ClassOpSig _ _ _ _) = (0,1,0,0)
422     sig_info (SpecSig _ _ _ _)    = (0,0,1,0)
423     sig_info (InlineSig _ _)      = (0,0,0,1)
424     sig_info _                    = (0,0,0,0)
425
426     import_info (ImportDecl _ qual as spec _)
427         = add6 (1, qual_info qual, as_info as, 0,0,0) (spec_info spec)
428     qual_info False  = 0
429     qual_info True   = 1
430     as_info Nothing  = 0
431     as_info (Just _) = 1
432     spec_info Nothing           = (0,0,0,1,0,0)
433     spec_info (Just (False, _)) = (0,0,0,0,1,0)
434     spec_info (Just (True, _))  = (0,0,0,0,0,1)
435
436     data_info (TyData _ _ _ constrs derivs _ _)
437         = (length constrs, case derivs of {Nothing -> 0; Just ds -> length ds})
438     data_info (TyNew _ _ _ constr derivs _ _)
439         = (length constr, case derivs of {Nothing -> 0; Just ds -> length ds})
440
441     class_info (ClassDecl _ _ _ meth_sigs def_meths _ _)
442         = case count_sigs meth_sigs of
443             (_,classops,_,_) ->
444                (classops, addpr (count_monobinds def_meths))
445
446     inst_info (InstDecl _ _ inst_meths _ _ inst_sigs _ _)
447         = case count_sigs inst_sigs of
448             (_,_,ss,is) ->
449                (addpr (count_monobinds inst_meths), ss, is)
450
451     is_type_decl (TySynonym _ _ _ _)     = True
452     is_type_decl _                       = False
453     is_data_decl (TyData _ _ _ _ _ _ _)  = True
454     is_data_decl _                       = False
455     is_newt_decl (TyNew  _ _ _ _ _ _ _)  = True
456     is_newt_decl _                       = False
457
458     addpr (x,y) = x+y
459     add1 x1 y1  = x1+y1
460     add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
461     add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
462     add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
463     add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
464     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)
465 \end{code}