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