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