0eb036c704ed3e54891f5b39a36893b59741d129
[ghc-hetmet.git] / ghc / compiler / main / Main.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
5
6 \begin{code}
7 module Main ( main ) where
8
9 #include "HsVersions.h"
10
11 import IO               ( hPutStr, stderr )
12 import HsSyn
13 import BasicTypes       ( NewOrData(..) )
14
15 import ReadPrefix       ( rdModule )
16 import Rename           ( renameModule )
17
18 import MkIface          ( startIface, ifaceDecls, endIface )
19 import TcModule         ( TcResults(..), typecheckModule )
20 import Desugar          ( deSugar )
21 import SimplCore        ( core2core )
22 import CoreLint         ( endPass )
23 import CoreTidy         ( tidyCorePgm )
24 import CoreToStg        ( topCoreBindsToStg )
25 import StgSyn           ( collectFinalStgBinders, pprStgBindings )
26 import SimplStg         ( stg2stg )
27 import CodeGen          ( codeGen )
28 import CodeOutput       ( codeOutput )
29
30 import Module           ( ModuleName, moduleNameUserString )
31 import AbsCSyn          ( absCNop )
32 import CmdLineOpts
33 import ErrUtils         ( ghcExit, doIfSet, dumpIfSet )
34 import Maybes           ( maybeToBool, MaybeErr(..) )
35 import TyCon            ( isDataTyCon )
36 import Class            ( classTyCon )
37 import UniqSupply       ( mkSplitUniqSupply )
38
39 import FiniteMap        ( emptyFM )
40 import Outputable
41 import Char             ( isSpace )
42 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
43 import SocketPrim
44 import BSD
45 import IOExts           ( unsafePerformIO )
46 import NativeInfo       ( os, arch )
47 #endif
48
49 \end{code}
50
51 \begin{code}
52 main =
53  --  _scc_ "main" 
54  doIt classifyOpts
55 \end{code}
56
57 \begin{code}
58 doIt :: ([CoreToDo], [StgToDo]) -> IO ()
59
60 doIt (core_cmds, stg_cmds)
61   = doIfSet opt_Verbose 
62         (hPutStr stderr "Glasgow Haskell Compiler, version "    >>
63          hPutStr stderr compiler_version                        >>
64          hPutStr stderr ", for Haskell 98\n")                   >>
65
66         --------------------------  Reader  ----------------
67     show_pass "Reader"  >>
68     _scc_     "Reader"
69     rdModule            >>= \ (mod_name, rdr_module) ->
70
71     dumpIfSet opt_D_source_stats "Source Statistics"
72         (ppSourceStats False rdr_module)                >>
73
74     -- UniqueSupplies for later use (these are the only lower case uniques)
75     mkSplitUniqSupply 'r'       >>= \ rn_uniqs  -> -- renamer
76     mkSplitUniqSupply 'a'       >>= \ tc_uniqs  -> -- typechecker
77     mkSplitUniqSupply 'd'       >>= \ ds_uniqs  -> -- desugarer
78     mkSplitUniqSupply 'r'       >>= \ ru_uniqs  -> -- rules
79     mkSplitUniqSupply 'c'       >>= \ c2s_uniqs -> -- core-to-stg
80     mkSplitUniqSupply 'u'       >>= \ tidy_uniqs -> -- tidy up
81     mkSplitUniqSupply 'g'       >>= \ st_uniqs  -> -- stg-to-stg passes
82     mkSplitUniqSupply 'n'       >>= \ ncg_uniqs -> -- native-code generator
83
84         --------------------------  Rename  ----------------
85     show_pass "Renamer"                         >>
86     _scc_     "Renamer"
87
88     renameModule rn_uniqs rdr_module            >>= \ maybe_rn_stuff ->
89     case maybe_rn_stuff of {
90         Nothing ->      -- Hurrah!  Renamer reckons that there's no need to
91                         -- go any further
92                         reportCompile mod_name "Compilation NOT required!" >>
93                         return ();
94         
95         Just (this_mod, rn_mod, iface_file_stuff, rn_name_supply, imported_modules) ->
96                         -- Oh well, we've got to recompile for real
97
98
99         --------------------------  Start interface file  ----------------
100     -- Safely past renaming: we can start the interface file:
101     -- (the iface file is produced incrementally, as we have
102     -- the information that we need...; we use "iface<blah>")
103     -- "endIface" finishes the job.
104     startIface this_mod iface_file_stuff        >>= \ if_handle ->
105
106
107         --------------------------  Typechecking ----------------
108     show_pass "TypeCheck"                               >>
109     _scc_     "TypeCheck"
110     typecheckModule tc_uniqs rn_name_supply
111                     iface_file_stuff rn_mod             >>= \ maybe_tc_stuff ->
112     case maybe_tc_stuff of {
113         Nothing -> ghcExit 1;   -- Type checker failed
114
115         Just (tc_results@(TcResults {tc_tycons  = local_tycons, 
116                                      tc_classes = local_classes, 
117                                      tc_insts   = inst_info })) ->
118
119
120         --------------------------  Desugaring ----------------
121     _scc_     "DeSugar"
122     deSugar this_mod ds_uniqs tc_results        >>= \ (desugared, rules, h_code, c_code) ->
123
124
125         --------------------------  Main Core-language transformations ----------------
126     _scc_     "Core2Core"
127     core2core core_cmds desugared rules                 >>= \ (simplified, imp_rule_ids) ->
128
129         -- Do the final tidy-up
130     tidyCorePgm tidy_uniqs this_mod
131                 simplified imp_rule_ids                 >>= \ (tidy_binds, tidy_imp_rule_ids) -> 
132
133
134         --------------------------  Convert to STG code -------------------------------
135     show_pass "Core2Stg"                        >>
136     _scc_     "Core2Stg"
137     let
138         stg_binds   = topCoreBindsToStg c2s_uniqs tidy_binds
139     in
140
141         --------------------------  Simplify STG code -------------------------------
142     show_pass "Stg2Stg"                         >>
143     _scc_     "Stg2Stg"
144     stg2stg stg_cmds this_mod st_uniqs stg_binds >>= \ (stg_binds2, cost_centre_info) ->
145
146
147         --------------------------  Interface file -------------------------------
148         -- Dump instance decls and type signatures into the interface file
149     _scc_     "Interface"
150     let
151         final_ids = collectFinalStgBinders (map fst stg_binds2)
152     in
153     ifaceDecls if_handle local_tycons local_classes 
154                inst_info final_ids tidy_binds imp_rule_ids      >>
155     endIface if_handle                                          >>
156             -- We are definitely done w/ interface-file stuff at this point:
157             -- (See comments near call to "startIface".)
158
159
160         --------------------------  Code generation -------------------------------
161     show_pass "CodeGen"                         >>
162     _scc_     "CodeGen"
163     codeGen this_mod imported_modules
164             cost_centre_info
165             local_tycons local_classes 
166             stg_binds2                          >>= \ abstractC ->
167
168
169         --------------------------  Code output -------------------------------
170     show_pass "CodeOutput"                              >>
171     _scc_     "CodeOutput"
172     codeOutput this_mod c_code h_code abstractC ncg_uniqs       >>
173
174
175         --------------------------  Final report -------------------------------
176     reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
177
178     ghcExit 0
179     } }
180   where
181     -------------------------------------------------------------
182     -- ****** help functions:
183
184     show_pass
185       = if opt_D_show_passes
186         then \ what -> hPutStr stderr ("*** "++what++":\n")
187         else \ what -> return ()
188
189 ppSourceStats short (HsModule name version exports imports decls src_loc)
190  = (if short then hcat else vcat)
191         (map pp_val
192                [("ExportAll        ", export_all), -- 1 if no export list
193                 ("ExportDecls      ", export_ds),
194                 ("ExportModules    ", export_ms),
195                 ("Imports          ", import_no),
196                 ("  ImpQual        ", import_qual),
197                 ("  ImpAs          ", import_as),
198                 ("  ImpAll         ", import_all),
199                 ("  ImpPartial     ", import_partial),
200                 ("  ImpHiding      ", import_hiding),
201                 ("FixityDecls      ", fixity_ds),
202                 ("DefaultDecls     ", default_ds),
203                 ("TypeDecls        ", type_ds),
204                 ("DataDecls        ", data_ds),
205                 ("NewTypeDecls     ", newt_ds),
206                 ("DataConstrs      ", data_constrs),
207                 ("DataDerivings    ", data_derivs),
208                 ("ClassDecls       ", class_ds),
209                 ("ClassMethods     ", class_method_ds),
210                 ("DefaultMethods   ", default_method_ds),
211                 ("InstDecls        ", inst_ds),
212                 ("InstMethods      ", inst_method_ds),
213                 ("TypeSigs         ", bind_tys),
214                 ("ValBinds         ", val_bind_ds),
215                 ("FunBinds         ", fn_bind_ds),
216                 ("InlineMeths      ", method_inlines),
217                 ("InlineBinds      ", bind_inlines),
218 --              ("SpecialisedData  ", data_specs),
219 --              ("SpecialisedInsts ", inst_specs),
220                 ("SpecialisedMeths ", method_specs),
221                 ("SpecialisedBinds ", bind_specs)
222                ])
223   where
224     pp_val (str, 0) = empty
225     pp_val (str, n) 
226       | not short   = hcat [text str, int n]
227       | otherwise   = hcat [text (trim str), equals, int n, semi]
228     
229     trim ls     = takeWhile (not.isSpace) (dropWhile isSpace ls)
230
231     fixity_ds   = length [() | FixD d <- decls]
232                 -- NB: this omits fixity decls on local bindings and
233                 -- in class decls.  ToDo
234
235     tycl_decls  = [d | TyClD d <- decls]
236     (class_ds, data_ds, newt_ds, type_ds) = countTyClDecls tycl_decls
237
238     inst_decls  = [d | InstD d <- decls]
239     inst_ds     = length inst_decls
240     default_ds  = length [() | DefD _ <- decls]
241     val_decls   = [d | ValD d <- decls]
242
243     real_exports = case exports of { Nothing -> []; Just es -> es }
244     n_exports    = length real_exports
245     export_ms    = length [() | IEModuleContents _ <- real_exports]
246     export_ds    = n_exports - export_ms
247     export_all   = case exports of { Nothing -> 1; other -> 0 }
248
249     (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
250         = count_binds (foldr ThenBinds EmptyBinds val_decls)
251
252     (import_no, import_qual, import_as, import_all, import_partial, import_hiding)
253         = foldr add6 (0,0,0,0,0,0) (map import_info imports)
254     (data_constrs, data_derivs)
255         = foldr add2 (0,0) (map data_info tycl_decls)
256     (class_method_ds, default_method_ds)
257         = foldr add2 (0,0) (map class_info tycl_decls)
258     (inst_method_ds, method_specs, method_inlines)
259         = foldr add3 (0,0,0) (map inst_info inst_decls)
260
261
262     count_binds EmptyBinds        = (0,0,0,0,0)
263     count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
264     count_binds (MonoBind b sigs _) = case (count_monobinds b, count_sigs sigs) of
265                                         ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
266
267     count_monobinds EmptyMonoBinds                 = (0,0)
268     count_monobinds (AndMonoBinds b1 b2)           = count_monobinds b1 `add2` count_monobinds b2
269     count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
270     count_monobinds (PatMonoBind p r _)            = (0,1)
271     count_monobinds (FunMonoBind f _ m _)          = (0,1)
272
273     count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
274
275     sig_info (Sig _ _ _)          = (1,0,0,0)
276     sig_info (ClassOpSig _ _ _ _) = (0,1,0,0)
277     sig_info (SpecSig _ _ _)      = (0,0,1,0)
278     sig_info (InlineSig _ _)      = (0,0,0,1)
279     sig_info _                    = (0,0,0,0)
280
281     import_info (ImportDecl _ _ qual as spec _)
282         = add6 (1, qual_info qual, as_info as, 0,0,0) (spec_info spec)
283     qual_info False  = 0
284     qual_info True   = 1
285     as_info Nothing  = 0
286     as_info (Just _) = 1
287     spec_info Nothing           = (0,0,0,1,0,0)
288     spec_info (Just (False, _)) = (0,0,0,0,1,0)
289     spec_info (Just (True, _))  = (0,0,0,0,0,1)
290
291     data_info (TyData _ _ _ _ constrs derivs _ _)
292         = (length constrs, case derivs of {Nothing -> 0; Just ds -> length ds})
293     data_info other = (0,0)
294
295     class_info (ClassDecl _ _ _ meth_sigs def_meths _ _ _ _ _)
296         = case count_sigs meth_sigs of
297             (_,classops,_,_) ->
298                (classops, addpr (count_monobinds def_meths))
299     class_info other = (0,0)
300
301     inst_info (InstDecl _ inst_meths inst_sigs _ _)
302         = case count_sigs inst_sigs of
303             (_,_,ss,is) ->
304                (addpr (count_monobinds inst_meths), ss, is)
305
306     addpr :: (Int,Int) -> Int
307     add1  :: Int -> Int -> Int
308     add2  :: (Int,Int) -> (Int,Int) -> (Int, Int)
309     add3  :: (Int,Int,Int) -> (Int,Int,Int) -> (Int, Int, Int)
310     add4  :: (Int,Int,Int,Int) -> (Int,Int,Int,Int) -> (Int, Int, Int, Int)
311     add5  :: (Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int)
312     add6  :: (Int,Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int, Int)
313
314     addpr (x,y) = x+y
315     add1 x1 y1  = x1+y1
316     add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
317     add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
318     add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
319     add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
320     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)
321 \end{code}
322
323 \begin{code}
324 compiler_version :: String
325 compiler_version =
326      case (show opt_HiVersion) of
327         [x]      -> ['0','.',x]
328         ls@[x,y] -> "0." ++ ls
329         ls       -> go ls
330  where
331   -- 10232353 => 10232.53
332   go ls@[x,y] = '.':ls
333   go (x:xs)   = x:go xs
334
335 \end{code}
336
337 \begin{code}
338 reportCompile :: ModuleName -> String -> IO ()
339 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
340 reportCompile mod_name info
341   | not opt_ReportCompile = return ()
342   | otherwise = (do 
343       sock <- udpSocket 0
344       addr <- motherShip
345       sendTo sock (moduleNameUserString mod_name ++ ';': compiler_version ++ 
346                    ';': os ++ ';':arch ++ '\n':' ':info ++ "\n") addr
347       return ()) `catch` (\ _ -> return ())
348
349 motherShip :: IO SockAddr
350 motherShip = do
351   he <- getHostByName "laysan.dcs.gla.ac.uk"
352   case (hostAddresses he) of
353     []    -> IOERROR (userError "No address!")
354     (x:_) -> return (SockAddrInet motherShipPort x)
355
356 --magick
357 motherShipPort :: PortNumber
358 motherShipPort = mkPortNumber 12345
359
360 -- creates a socket capable of sending datagrams,
361 -- binding it to a port
362 --  ( 0 => have the system pick next available port no.)
363 udpSocket :: Int -> IO Socket
364 udpSocket p = do
365   pr <- getProtocolNumber "udp"
366   s  <- socket AF_INET Datagram pr
367   bindSocket s (SockAddrInet (mkPortNumber p) iNADDR_ANY)
368   return s
369 #else
370 reportCompile _ _ = return ()
371 #endif
372
373 \end{code}