[project @ 2000-06-18 08:37:17 by simonpj]
[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          ( writeIface )
25 import TcModule         ( TcResults(..), typecheckModule )
26 import Desugar          ( deSugar )
27 import SimplCore        ( core2core )
28 import OccurAnal        ( occurAnalyseBinds )
29 import CoreLint         ( endPass )
30 import CoreUtils        ( coreBindsSize )
31 import CoreTidy         ( tidyCorePgm )
32 import CoreToStg        ( topCoreBindsToStg )
33 import StgSyn           ( collectFinalStgBinders, pprStgBindings )
34 import SimplStg         ( stg2stg )
35 import CodeGen          ( codeGen )
36 import CodeOutput       ( codeOutput )
37
38 import Module           ( ModuleName, moduleNameUserString )
39 import AbsCSyn          ( absCNop )
40 import CmdLineOpts
41 import ErrUtils         ( ghcExit, doIfSet, dumpIfSet )
42 import Maybes           ( maybeToBool, MaybeErr(..) )
43 import TyCon            ( isDataTyCon )
44 import Class            ( classTyCon )
45 import UniqSupply       ( mkSplitUniqSupply )
46
47 import FiniteMap        ( emptyFM )
48 import Outputable
49 import Char             ( isSpace )
50 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
51 import SocketPrim
52 import BSD
53 import IOExts           ( unsafePerformIO )
54 import NativeInfo       ( os, arch )
55 #endif
56
57 \end{code}
58
59 \begin{code}
60 main = stderr `seq`     -- Bug fix.  Sigh
61  --  _scc_ "main" 
62  doIt classifyOpts
63 \end{code}
64
65 \begin{code}
66 parseModule :: IO (ModuleName, RdrNameHsModule)
67 parseModule = do
68     buf <- hGetStringBuffer True{-expand tabs-} (unpackFS src_filename)
69     case parse buf PState{ bol = 0#, atbol = 1#,
70                            context = [], glasgow_exts = glaexts,
71                            loc = mkSrcLoc src_filename 1 } of
72
73         PFailed err -> do
74                 printErrs err
75                 ghcExit 1
76                 return (error "parseModule") -- just to get the types right
77
78         POk _ m@(HsModule mod _ _ _ _ _ _) -> 
79                 return (mod, m)
80   where
81         glaexts | opt_GlasgowExts = 1#
82                 | otherwise       = 0#
83 \end{code}
84
85 \begin{code}
86 doIt :: ([CoreToDo], [StgToDo]) -> IO ()
87
88 doIt (core_cmds, stg_cmds)
89   = doIfSet opt_Verbose 
90         (hPutStr stderr "Glasgow Haskell Compiler, version "    >>
91          hPutStr stderr compiler_version                        >>
92          hPutStr stderr ", for Haskell 98, compiled by GHC version " >>
93          hPutStr stderr booter_version                          >>
94          hPutStr stderr "\n")                                   >>
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
188         --------------------------  Interface file -------------------------------
189         -- Dump instance decls and type signatures into the interface file
190     _scc_     "Interface"
191     let
192         final_ids = collectFinalStgBinders (map fst stg_binds2)
193     in
194     writeIface this_mod old_iface new_iface
195                local_tycons local_classes inst_info
196                final_ids occ_anal_tidy_binds tidy_orphan_rules          >>
197
198
199         --------------------------  Code generation -------------------------------
200     show_pass "CodeGen"                         >>
201     _scc_     "CodeGen"
202     codeGen this_mod imported_modules
203             cost_centre_info
204             fe_binders
205             local_tycons local_classes 
206             stg_binds2                          >>= \ abstractC ->
207
208
209         --------------------------  Code output -------------------------------
210     show_pass "CodeOutput"                              >>
211     _scc_     "CodeOutput"
212     codeOutput this_mod local_tycons local_classes
213                occ_anal_tidy_binds stg_binds2
214                c_code h_code abstractC 
215                ncg_uniqs                                >>
216
217
218         --------------------------  Final report -------------------------------
219     reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
220
221     ghcExit 0
222     } }
223   where
224     -------------------------------------------------------------
225     -- ****** help functions:
226
227     show_pass
228       = if opt_D_show_passes
229         then \ what -> hPutStr stderr ("*** "++what++":\n")
230         else \ what -> return ()
231
232 ppSourceStats short (HsModule name version exports imports decls _ src_loc)
233  = (if short then hcat else vcat)
234         (map pp_val
235                [("ExportAll        ", export_all), -- 1 if no export list
236                 ("ExportDecls      ", export_ds),
237                 ("ExportModules    ", export_ms),
238                 ("Imports          ", import_no),
239                 ("  ImpQual        ", import_qual),
240                 ("  ImpAs          ", import_as),
241                 ("  ImpAll         ", import_all),
242                 ("  ImpPartial     ", import_partial),
243                 ("  ImpHiding      ", import_hiding),
244                 ("FixityDecls      ", fixity_ds),
245                 ("DefaultDecls     ", default_ds),
246                 ("TypeDecls        ", type_ds),
247                 ("DataDecls        ", data_ds),
248                 ("NewTypeDecls     ", newt_ds),
249                 ("DataConstrs      ", data_constrs),
250                 ("DataDerivings    ", data_derivs),
251                 ("ClassDecls       ", class_ds),
252                 ("ClassMethods     ", class_method_ds),
253                 ("DefaultMethods   ", default_method_ds),
254                 ("InstDecls        ", inst_ds),
255                 ("InstMethods      ", inst_method_ds),
256                 ("TypeSigs         ", bind_tys),
257                 ("ValBinds         ", val_bind_ds),
258                 ("FunBinds         ", fn_bind_ds),
259                 ("InlineMeths      ", method_inlines),
260                 ("InlineBinds      ", bind_inlines),
261 --              ("SpecialisedData  ", data_specs),
262 --              ("SpecialisedInsts ", inst_specs),
263                 ("SpecialisedMeths ", method_specs),
264                 ("SpecialisedBinds ", bind_specs)
265                ])
266   where
267     pp_val (str, 0) = empty
268     pp_val (str, n) 
269       | not short   = hcat [text str, int n]
270       | otherwise   = hcat [text (trim str), equals, int n, semi]
271     
272     trim ls     = takeWhile (not.isSpace) (dropWhile isSpace ls)
273
274     fixity_ds   = length [() | FixD d <- decls]
275                 -- NB: this omits fixity decls on local bindings and
276                 -- in class decls.  ToDo
277
278     tycl_decls  = [d | TyClD d <- decls]
279     (class_ds, data_ds, newt_ds, type_ds) = countTyClDecls tycl_decls
280
281     inst_decls  = [d | InstD d <- decls]
282     inst_ds     = length inst_decls
283     default_ds  = length [() | DefD _ <- decls]
284     val_decls   = [d | ValD d <- decls]
285
286     real_exports = case exports of { Nothing -> []; Just es -> es }
287     n_exports    = length real_exports
288     export_ms    = length [() | IEModuleContents _ <- real_exports]
289     export_ds    = n_exports - export_ms
290     export_all   = case exports of { Nothing -> 1; other -> 0 }
291
292     (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
293         = count_binds (foldr ThenBinds EmptyBinds val_decls)
294
295     (import_no, import_qual, import_as, import_all, import_partial, import_hiding)
296         = foldr add6 (0,0,0,0,0,0) (map import_info imports)
297     (data_constrs, data_derivs)
298         = foldr add2 (0,0) (map data_info tycl_decls)
299     (class_method_ds, default_method_ds)
300         = foldr add2 (0,0) (map class_info tycl_decls)
301     (inst_method_ds, method_specs, method_inlines)
302         = foldr add3 (0,0,0) (map inst_info inst_decls)
303
304
305     count_binds EmptyBinds        = (0,0,0,0,0)
306     count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
307     count_binds (MonoBind b sigs _) = case (count_monobinds b, count_sigs sigs) of
308                                         ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
309
310     count_monobinds EmptyMonoBinds                 = (0,0)
311     count_monobinds (AndMonoBinds b1 b2)           = count_monobinds b1 `add2` count_monobinds b2
312     count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
313     count_monobinds (PatMonoBind p r _)            = (0,1)
314     count_monobinds (FunMonoBind f _ m _)          = (0,1)
315
316     count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
317
318     sig_info (Sig _ _ _)            = (1,0,0,0)
319     sig_info (ClassOpSig _ _ _ _ _) = (0,1,0,0)
320     sig_info (SpecSig _ _ _)        = (0,0,1,0)
321     sig_info (InlineSig _ _ _)      = (0,0,0,1)
322     sig_info (NoInlineSig _ _ _)    = (0,0,0,1)
323     sig_info _                      = (0,0,0,0)
324
325     import_info (ImportDecl _ _ qual as spec _)
326         = add6 (1, qual_info qual, as_info as, 0,0,0) (spec_info spec)
327     qual_info False  = 0
328     qual_info True   = 1
329     as_info Nothing  = 0
330     as_info (Just _) = 1
331     spec_info Nothing           = (0,0,0,1,0,0)
332     spec_info (Just (False, _)) = (0,0,0,0,1,0)
333     spec_info (Just (True, _))  = (0,0,0,0,0,1)
334
335     data_info (TyData _ _ _ _ _ nconstrs derivs _ _)
336         = (nconstrs, case derivs of {Nothing -> 0; Just ds -> length ds})
337     data_info other = (0,0)
338
339     class_info (ClassDecl _ _ _ _ meth_sigs def_meths _ _ _ _ _ _)
340         = case count_sigs meth_sigs of
341             (_,classops,_,_) ->
342                (classops, addpr (count_monobinds def_meths))
343     class_info other = (0,0)
344
345     inst_info (InstDecl _ inst_meths inst_sigs _ _)
346         = case count_sigs inst_sigs of
347             (_,_,ss,is) ->
348                (addpr (count_monobinds inst_meths), ss, is)
349
350     addpr :: (Int,Int) -> Int
351     add1  :: Int -> Int -> Int
352     add2  :: (Int,Int) -> (Int,Int) -> (Int, Int)
353     add3  :: (Int,Int,Int) -> (Int,Int,Int) -> (Int, Int, Int)
354     add4  :: (Int,Int,Int,Int) -> (Int,Int,Int,Int) -> (Int, Int, Int, Int)
355     add5  :: (Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int)
356     add6  :: (Int,Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int, Int)
357
358     addpr (x,y) = x+y
359     add1 x1 y1  = x1+y1
360     add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
361     add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
362     add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
363     add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
364     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)
365 \end{code}
366
367 \begin{code}
368 compiler_version :: String
369 compiler_version =
370      case (show opt_HiVersion) of
371         [x]      -> ['0','.',x]
372         ls@[x,y] -> "0." ++ ls
373         ls       -> go ls
374  where
375   -- 10232353 => 10232.53
376   go ls@[x,y] = '.':ls
377   go (x:xs)   = x:go xs
378
379 booter_version
380  = case "\ 
381         \ __GLASGOW_HASKELL__" of
382     ' ':n:ns -> n:'.':ns
383     ' ':m    -> m
384 \end{code}
385
386 \begin{code}
387 reportCompile :: ModuleName -> String -> IO ()
388 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
389 reportCompile mod_name info
390   | not opt_ReportCompile = return ()
391   | otherwise = (do 
392       sock <- udpSocket 0
393       addr <- motherShip
394       sendTo sock (moduleNameUserString mod_name ++ ';': compiler_version ++ 
395                    ';': os ++ ';':arch ++ '\n':' ':info ++ "\n") addr
396       return ()) `catch` (\ _ -> return ())
397
398 motherShip :: IO SockAddr
399 motherShip = do
400   he <- getHostByName "laysan.dcs.gla.ac.uk"
401   case (hostAddresses he) of
402     []    -> IOERROR (userError "No address!")
403     (x:_) -> return (SockAddrInet motherShipPort x)
404
405 --magick
406 motherShipPort :: PortNumber
407 motherShipPort = mkPortNumber 12345
408
409 -- creates a socket capable of sending datagrams,
410 -- binding it to a port
411 --  ( 0 => have the system pick next available port no.)
412 udpSocket :: Int -> IO Socket
413 udpSocket p = do
414   pr <- getProtocolNumber "udp"
415   s  <- socket AF_INET Datagram pr
416   bindSocket s (SockAddrInet (mkPortNumber p) iNADDR_ANY)
417   return s
418 #else
419 reportCompile _ _ = return ()
420 #endif
421
422 \end{code}