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