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