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