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