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