[project @ 2000-03-24 17:49:29 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 import RnMonad          ( InterfaceDetails(..) )
24
25 import MkIface          ( startIface, ifaceDecls, endIface )
26 import TcModule         ( TcResults(..), typecheckModule )
27 import Desugar          ( deSugar )
28 import SimplCore        ( core2core )
29 import CoreLint         ( endPass )
30 import CoreSyn          ( 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, iface_file_stuff@(InterfaceDetails _ _ _ deprecations),
128               rn_name_supply, imported_modules) ->
129                         -- Oh well, we've got to recompile for real
130
131
132         --------------------------  Start interface file  ----------------
133     -- Safely past renaming: we can start the interface file:
134     -- (the iface file is produced incrementally, as we have
135     -- the information that we need...; we use "iface<blah>")
136     -- "endIface" finishes the job.
137     startIface this_mod iface_file_stuff        >>= \ if_handle ->
138
139
140         --------------------------  Typechecking ----------------
141     show_pass "TypeCheck"                               >>
142     _scc_     "TypeCheck"
143     typecheckModule tc_uniqs rn_name_supply
144                     iface_file_stuff rn_mod             >>= \ maybe_tc_stuff ->
145     case maybe_tc_stuff of {
146         Nothing -> ghcExit 1;   -- Type checker failed
147
148         Just (tc_results@(TcResults {tc_tycons  = local_tycons, 
149                                      tc_classes = local_classes, 
150                                      tc_insts   = inst_info })) ->
151
152
153         --------------------------  Desugaring ----------------
154     _scc_     "DeSugar"
155     deSugar this_mod ds_uniqs tc_results        >>= \ (desugared, rules, h_code, c_code, fe_binders) ->
156
157
158         --------------------------  Main Core-language transformations ----------------
159     _scc_     "Core2Core"
160     core2core core_cmds desugared rules                 >>= \ (simplified, orphan_rules) ->
161
162         -- Do the final tidy-up
163     tidyCorePgm tidy_uniqs this_mod
164                 simplified orphan_rules                 >>= \ (tidy_binds, tidy_orphan_rules) -> 
165
166
167         --------------------------  Convert to STG code -------------------------------
168     show_pass "Core2Stg"                        >>
169     _scc_     "Core2Stg"
170     let
171         stg_binds   = topCoreBindsToStg c2s_uniqs tidy_binds
172     in
173
174         --------------------------  Simplify STG code -------------------------------
175     show_pass "Stg2Stg"                         >>
176     _scc_     "Stg2Stg"
177     stg2stg stg_cmds this_mod st_uniqs stg_binds >>= \ (stg_binds2, cost_centre_info) ->
178
179
180         --------------------------  Interface file -------------------------------
181         -- Dump instance decls and type signatures into the interface file
182     _scc_     "Interface"
183     let
184         final_ids = collectFinalStgBinders (map fst stg_binds2)
185     in
186     coreBindsSize tidy_binds `seq`
187 --      TEMP: the above call zaps some space usage allocated by the
188 --      simplifier, which for reasons I don't understand, persists
189 --      thoroughout code generation
190
191     ifaceDecls if_handle local_tycons local_classes inst_info
192                final_ids tidy_binds tidy_orphan_rules deprecations      >>
193     endIface if_handle                                          >>
194             -- We are definitely done w/ interface-file stuff at this point:
195             -- (See comments near call to "startIface".)
196
197
198         --------------------------  Code generation -------------------------------
199     show_pass "CodeGen"                         >>
200     _scc_     "CodeGen"
201     codeGen this_mod imported_modules
202             cost_centre_info
203             fe_binders
204             local_tycons local_classes 
205             stg_binds2                          >>= \ abstractC ->
206
207
208         --------------------------  Code output -------------------------------
209     show_pass "CodeOutput"                              >>
210     _scc_     "CodeOutput"
211     codeOutput this_mod local_tycons local_classes stg_binds2
212                c_code h_code abstractC 
213                ncg_uniqs                                >>
214
215
216         --------------------------  Final report -------------------------------
217     reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
218
219     ghcExit 0
220     } }
221   where
222     -------------------------------------------------------------
223     -- ****** help functions:
224
225     show_pass
226       = if opt_D_show_passes
227         then \ what -> hPutStr stderr ("*** "++what++":\n")
228         else \ what -> return ()
229
230 ppSourceStats short (HsModule name version exports imports decls _ src_loc)
231  = (if short then hcat else vcat)
232         (map pp_val
233                [("ExportAll        ", export_all), -- 1 if no export list
234                 ("ExportDecls      ", export_ds),
235                 ("ExportModules    ", export_ms),
236                 ("Imports          ", import_no),
237                 ("  ImpQual        ", import_qual),
238                 ("  ImpAs          ", import_as),
239                 ("  ImpAll         ", import_all),
240                 ("  ImpPartial     ", import_partial),
241                 ("  ImpHiding      ", import_hiding),
242                 ("FixityDecls      ", fixity_ds),
243                 ("DefaultDecls     ", default_ds),
244                 ("TypeDecls        ", type_ds),
245                 ("DataDecls        ", data_ds),
246                 ("NewTypeDecls     ", newt_ds),
247                 ("DataConstrs      ", data_constrs),
248                 ("DataDerivings    ", data_derivs),
249                 ("ClassDecls       ", class_ds),
250                 ("ClassMethods     ", class_method_ds),
251                 ("DefaultMethods   ", default_method_ds),
252                 ("InstDecls        ", inst_ds),
253                 ("InstMethods      ", inst_method_ds),
254                 ("TypeSigs         ", bind_tys),
255                 ("ValBinds         ", val_bind_ds),
256                 ("FunBinds         ", fn_bind_ds),
257                 ("InlineMeths      ", method_inlines),
258                 ("InlineBinds      ", bind_inlines),
259 --              ("SpecialisedData  ", data_specs),
260 --              ("SpecialisedInsts ", inst_specs),
261                 ("SpecialisedMeths ", method_specs),
262                 ("SpecialisedBinds ", bind_specs)
263                ])
264   where
265     pp_val (str, 0) = empty
266     pp_val (str, n) 
267       | not short   = hcat [text str, int n]
268       | otherwise   = hcat [text (trim str), equals, int n, semi]
269     
270     trim ls     = takeWhile (not.isSpace) (dropWhile isSpace ls)
271
272     fixity_ds   = length [() | FixD d <- decls]
273                 -- NB: this omits fixity decls on local bindings and
274                 -- in class decls.  ToDo
275
276     tycl_decls  = [d | TyClD d <- decls]
277     (class_ds, data_ds, newt_ds, type_ds) = countTyClDecls tycl_decls
278
279     inst_decls  = [d | InstD d <- decls]
280     inst_ds     = length inst_decls
281     default_ds  = length [() | DefD _ <- decls]
282     val_decls   = [d | ValD d <- decls]
283
284     real_exports = case exports of { Nothing -> []; Just es -> es }
285     n_exports    = length real_exports
286     export_ms    = length [() | IEModuleContents _ <- real_exports]
287     export_ds    = n_exports - export_ms
288     export_all   = case exports of { Nothing -> 1; other -> 0 }
289
290     (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
291         = count_binds (foldr ThenBinds EmptyBinds val_decls)
292
293     (import_no, import_qual, import_as, import_all, import_partial, import_hiding)
294         = foldr add6 (0,0,0,0,0,0) (map import_info imports)
295     (data_constrs, data_derivs)
296         = foldr add2 (0,0) (map data_info tycl_decls)
297     (class_method_ds, default_method_ds)
298         = foldr add2 (0,0) (map class_info tycl_decls)
299     (inst_method_ds, method_specs, method_inlines)
300         = foldr add3 (0,0,0) (map inst_info inst_decls)
301
302
303     count_binds EmptyBinds        = (0,0,0,0,0)
304     count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
305     count_binds (MonoBind b sigs _) = case (count_monobinds b, count_sigs sigs) of
306                                         ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
307
308     count_monobinds EmptyMonoBinds                 = (0,0)
309     count_monobinds (AndMonoBinds b1 b2)           = count_monobinds b1 `add2` count_monobinds b2
310     count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
311     count_monobinds (PatMonoBind p r _)            = (0,1)
312     count_monobinds (FunMonoBind f _ m _)          = (0,1)
313
314     count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
315
316     sig_info (Sig _ _ _)            = (1,0,0,0)
317     sig_info (ClassOpSig _ _ _ _ _) = (0,1,0,0)
318     sig_info (SpecSig _ _ _)        = (0,0,1,0)
319     sig_info (InlineSig _ _ _)      = (0,0,0,1)
320     sig_info (NoInlineSig _ _ _)    = (0,0,0,1)
321     sig_info _                      = (0,0,0,0)
322
323     import_info (ImportDecl _ _ qual as spec _)
324         = add6 (1, qual_info qual, as_info as, 0,0,0) (spec_info spec)
325     qual_info False  = 0
326     qual_info True   = 1
327     as_info Nothing  = 0
328     as_info (Just _) = 1
329     spec_info Nothing           = (0,0,0,1,0,0)
330     spec_info (Just (False, _)) = (0,0,0,0,1,0)
331     spec_info (Just (True, _))  = (0,0,0,0,0,1)
332
333     data_info (TyData _ _ _ _ constrs derivs _ _)
334         = (length constrs, case derivs of {Nothing -> 0; Just ds -> length ds})
335     data_info other = (0,0)
336
337     class_info (ClassDecl _ _ _ _ meth_sigs def_meths _ _ _ _ _ _)
338         = case count_sigs meth_sigs of
339             (_,classops,_,_) ->
340                (classops, addpr (count_monobinds def_meths))
341     class_info other = (0,0)
342
343     inst_info (InstDecl _ inst_meths inst_sigs _ _)
344         = case count_sigs inst_sigs of
345             (_,_,ss,is) ->
346                (addpr (count_monobinds inst_meths), ss, is)
347
348     addpr :: (Int,Int) -> Int
349     add1  :: Int -> Int -> Int
350     add2  :: (Int,Int) -> (Int,Int) -> (Int, Int)
351     add3  :: (Int,Int,Int) -> (Int,Int,Int) -> (Int, Int, Int)
352     add4  :: (Int,Int,Int,Int) -> (Int,Int,Int,Int) -> (Int, Int, Int, Int)
353     add5  :: (Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int)
354     add6  :: (Int,Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int, Int)
355
356     addpr (x,y) = x+y
357     add1 x1 y1  = x1+y1
358     add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
359     add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
360     add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
361     add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
362     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)
363 \end{code}
364
365 \begin{code}
366 compiler_version :: String
367 compiler_version =
368      case (show opt_HiVersion) of
369         [x]      -> ['0','.',x]
370         ls@[x,y] -> "0." ++ ls
371         ls       -> go ls
372  where
373   -- 10232353 => 10232.53
374   go ls@[x,y] = '.':ls
375   go (x:xs)   = x:go xs
376
377 booter_version
378  = case "\ 
379         \ __GLASGOW_HASKELL__" of
380     ' ':n:ns -> n:'.':ns
381     ' ':m    -> m
382 \end{code}
383
384 \begin{code}
385 reportCompile :: ModuleName -> String -> IO ()
386 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
387 reportCompile mod_name info
388   | not opt_ReportCompile = return ()
389   | otherwise = (do 
390       sock <- udpSocket 0
391       addr <- motherShip
392       sendTo sock (moduleNameUserString mod_name ++ ';': compiler_version ++ 
393                    ';': os ++ ';':arch ++ '\n':' ':info ++ "\n") addr
394       return ()) `catch` (\ _ -> return ())
395
396 motherShip :: IO SockAddr
397 motherShip = do
398   he <- getHostByName "laysan.dcs.gla.ac.uk"
399   case (hostAddresses he) of
400     []    -> IOERROR (userError "No address!")
401     (x:_) -> return (SockAddrInet motherShipPort x)
402
403 --magick
404 motherShipPort :: PortNumber
405 motherShipPort = mkPortNumber 12345
406
407 -- creates a socket capable of sending datagrams,
408 -- binding it to a port
409 --  ( 0 => have the system pick next available port no.)
410 udpSocket :: Int -> IO Socket
411 udpSocket p = do
412   pr <- getProtocolNumber "udp"
413   s  <- socket AF_INET Datagram pr
414   bindSocket s (SockAddrInet (mkPortNumber p) iNADDR_ANY)
415   return s
416 #else
417 reportCompile _ _ = return ()
418 #endif
419
420 \end{code}