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