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