[project @ 2000-10-23 09:03:26 by simonpj]
[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 PrelInfo         ( wiredInThings )
24 import MkIface          ( writeIface )
25 import TcModule         ( TcResults(..), typecheckModule )
26 import Desugar          ( deSugar )
27 import SimplCore        ( core2core )
28 import OccurAnal        ( occurAnalyseBinds )
29 import CoreUtils        ( coreBindsSize )
30 import CoreTidy         ( tidyCorePgm )
31 import CoreToStg        ( topCoreBindsToStg )
32 import StgSyn           ( collectFinalStgBinders )
33 import SimplStg         ( stg2stg )
34 import CodeGen          ( codeGen )
35 import CodeOutput       ( codeOutput )
36
37 import Module           ( ModuleName, moduleNameUserString )
38 import CmdLineOpts
39 import ErrUtils         ( ghcExit, doIfSet, dumpIfSet )
40 import UniqSupply       ( mkSplitUniqSupply )
41
42 import Outputable
43 import Char             ( isSpace )
44 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
45 import SocketPrim
46 import BSD
47 import IOExts           ( unsafePerformIO )
48 import NativeInfo       ( os, arch )
49 #endif
50 import StgInterp        ( runStgI )
51 \end{code}
52
53
54 %************************************************************************
55 %*                                                                      *
56 \subsection{The main compiler pipeline}
57 %*                                                                      *
58 %************************************************************************
59
60 \begin{code}
61 data HscResult
62    = HscOK   ModDetails              -- new details (HomeSymbolTable additions)
63              (Maybe ModIface)        -- new iface (if any compilation was done)
64              (Maybe String)          -- generated stub_h filename (in /tmp)
65              (Maybe String)          -- generated stub_c filename (in /tmp)
66              (Maybe [UnlinkedIBind]) -- interpreted code, if any
67              PersistentCompilerState -- updated PCS
68              (Bag WarnMsg)              -- warnings
69
70    | HscErrs PersistentCompilerState -- updated PCS
71              (Bag ErrMsg)               -- errors
72              (Bag WarnMsg)             -- warnings
73
74 hscMain
75   :: DynFlags   
76   -> ModSummary       -- summary, including source filename
77   -> Maybe ModIFace   -- old interface, if available
78   -> String           -- file in which to put the output (.s, .hc, .java etc.)
79   -> HomeSymbolTable            -- for home module ModDetails
80   -> PersistentCompilerState    -- IN: persistent compiler state
81   -> IO HscResult
82
83 hscMain flags core_cmds stg_cmds summary maybe_old_iface
84         output_filename mod_details pcs1 =
85
86         --------------------------  Reader  ----------------
87     show_pass "Parser"  >>
88     _scc_     "Parser"
89
90     let src_filename -- name of the preprocessed source file
91        = case ms_ppsource summary of
92             Just (filename, fingerprint) -> filename
93             Nothing -> pprPanic "hscMain:summary is not of a source module"
94                                 (ppr summary)
95
96     buf <- hGetStringBuffer True{-expand tabs-} src_filename
97
98     let glaexts | opt_GlasgowExts = 1#
99                 | otherwise       = 0#
100
101     case parse buf PState{ bol = 0#, atbol = 1#,
102                            context = [], glasgow_exts = glaexts,
103                            loc = mkSrcLoc src_filename 1 } of {
104
105         PFailed err -> return (CompErrs pcs err)
106
107         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) ->
108
109     dumpIfSet (dopt_D_dump_parsed flags) "Parser" (ppr rdr_module) >>
110
111     dumpIfSet (dopt_D_source_stats flags) "Source Statistics"
112         (ppSourceStats False rdr_module)                >>
113
114     -- UniqueSupplies for later use (these are the only lower case uniques)
115     mkSplitUniqSupply 'd'       >>= \ ds_uniqs  -> -- desugarer
116     mkSplitUniqSupply 'r'       >>= \ ru_uniqs  -> -- rules
117     mkSplitUniqSupply 'c'       >>= \ c2s_uniqs -> -- core-to-stg
118     mkSplitUniqSupply 'u'       >>= \ tidy_uniqs -> -- tidy up
119     mkSplitUniqSupply 'g'       >>= \ st_uniqs  -> -- stg-to-stg passes
120     mkSplitUniqSupply 'n'       >>= \ ncg_uniqs -> -- native-code generator
121
122         --------------------------  Rename  ----------------
123     show_pass "Renamer"                         >>
124     _scc_     "Renamer"
125
126     renameModule rn_uniqs rdr_module            >>= \ maybe_rn_stuff ->
127     case maybe_rn_stuff of {
128         Nothing ->      -- Hurrah!  Renamer reckons that there's no need to
129                         -- go any further
130                         reportCompile mod_name "Compilation NOT required!" >>
131                         return ();
132         
133         Just (this_mod, rn_mod, 
134               old_iface, new_iface,
135               rn_name_supply, fixity_env,
136               imported_modules) ->
137                         -- Oh well, we've got to recompile for real
138
139
140         --------------------------  Typechecking ----------------
141     show_pass "TypeCheck"                               >>
142     _scc_     "TypeCheck"
143     typecheckModule tc_uniqs rn_name_supply
144                     fixity_env 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         -- Run the occurrence analyser one last time, so that
167         -- dead binders get dead-binder info.  This is exploited by
168         -- code generators to avoid spitting out redundant bindings.
169         -- The occurrence-zapping in Simplify.simplCaseBinder means
170         -- that the Simplifier nukes useful dead-var stuff especially
171         -- in case patterns.
172     let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds in
173
174     coreBindsSize occ_anal_tidy_binds `seq`
175 --      TEMP: the above call zaps some space usage allocated by the
176 --      simplifier, which for reasons I don't understand, persists
177 --      thoroughout code generation
178
179
180
181         --------------------------  Convert to STG code -------------------------------
182     show_pass "Core2Stg"                        >>
183     _scc_     "Core2Stg"
184     let
185         stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
186     in
187
188         --------------------------  Simplify STG code -------------------------------
189     show_pass "Stg2Stg"                          >>
190     _scc_     "Stg2Stg"
191     stg2stg stg_cmds this_mod st_uniqs stg_binds >>= \ (stg_binds2, cost_centre_info) ->
192
193 #ifdef GHCI
194     runStgI local_tycons local_classes 
195                          (map fst stg_binds2)    >>= \ i_result ->
196     putStr ("\nANSWER = " ++ show i_result ++ "\n\n")
197     >>
198
199 #else
200         --------------------------  Interface file -------------------------------
201         -- Dump instance decls and type signatures into the interface file
202     _scc_     "Interface"
203     let
204         final_ids = collectFinalStgBinders (map fst stg_binds2)
205     in
206     writeIface this_mod old_iface new_iface
207                local_tycons local_classes inst_info
208                final_ids occ_anal_tidy_binds tidy_orphan_rules          >>
209
210
211         --------------------------  Code generation -------------------------------
212     show_pass "CodeGen"                         >>
213     _scc_     "CodeGen"
214     codeGen this_mod imported_modules
215             cost_centre_info
216             fe_binders
217             local_tycons local_classes 
218             stg_binds2                          >>= \ abstractC ->
219
220
221         --------------------------  Code output -------------------------------
222     show_pass "CodeOutput"                              >>
223     _scc_     "CodeOutput"
224     codeOutput this_mod local_tycons local_classes
225                occ_anal_tidy_binds stg_binds2
226                c_code h_code abstractC 
227                ncg_uniqs                                >>
228
229
230         --------------------------  Final report -------------------------------
231     reportCompile mod_name (showSDoc (ppSourceStats True rdr_module)) >>
232
233 #endif
234
235
236     ghcExit 0
237     } }
238   where
239     -------------------------------------------------------------
240     -- ****** help functions:
241
242     show_pass
243       = if opt_D_show_passes
244         then \ what -> hPutStr stderr ("*** "++what++":\n")
245         else \ what -> return ()
246 \end{code}
247
248
249 %************************************************************************
250 %*                                                                      *
251 \subsection{Initial persistent state}
252 %*                                                                      *
253 %************************************************************************
254
255 \begin{code}
256 initPersistentCompilerState :: PersistentCompilerState
257 initPersistentCompilerState 
258   = PCS { pcs_PST   = initPackageDetails,
259           pcs_insts = emptyInstEnv,
260           pcs_rules = emptyRuleEnv,
261           pcs_PRS   = initPersistentRenamerState }
262
263 initPackageDetails :: PackageSymbolTable
264 initPackageDetails = extendTypeEnv emptyModuleEnv wiredInThings
265
266 initPersistentRenamerState :: PersistentRenamerState
267   = PRS { prsOrig  = Orig { origNames  = initOrigNames,
268                             origIParam = emptyFM },
269           prsDecls = emptyNameEnv,
270           prsInsts = emptyBag,
271           prsRules = emptyBag
272     }
273
274 initOrigNames :: FiniteMap (ModuleName,OccName) Name
275 initOrigNames = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
276               where
277                 grab names   = foldl add emptyFM names
278                 add env name = addToFM env (moduleName (nameModule name), nameOccName name) name
279 \end{code}
280
281 %************************************************************************
282 %*                                                                      *
283 \subsection{Statistics}
284 %*                                                                      *
285 %************************************************************************
286
287 \begin{code}
288 ppSourceStats short (HsModule name version exports imports decls _ src_loc)
289  = (if short then hcat else vcat)
290         (map pp_val
291                [("ExportAll        ", export_all), -- 1 if no export list
292                 ("ExportDecls      ", export_ds),
293                 ("ExportModules    ", export_ms),
294                 ("Imports          ", import_no),
295                 ("  ImpQual        ", import_qual),
296                 ("  ImpAs          ", import_as),
297                 ("  ImpAll         ", import_all),
298                 ("  ImpPartial     ", import_partial),
299                 ("  ImpHiding      ", import_hiding),
300                 ("FixityDecls      ", fixity_ds),
301                 ("DefaultDecls     ", default_ds),
302                 ("TypeDecls        ", type_ds),
303                 ("DataDecls        ", data_ds),
304                 ("NewTypeDecls     ", newt_ds),
305                 ("DataConstrs      ", data_constrs),
306                 ("DataDerivings    ", data_derivs),
307                 ("ClassDecls       ", class_ds),
308                 ("ClassMethods     ", class_method_ds),
309                 ("DefaultMethods   ", default_method_ds),
310                 ("InstDecls        ", inst_ds),
311                 ("InstMethods      ", inst_method_ds),
312                 ("TypeSigs         ", bind_tys),
313                 ("ValBinds         ", val_bind_ds),
314                 ("FunBinds         ", fn_bind_ds),
315                 ("InlineMeths      ", method_inlines),
316                 ("InlineBinds      ", bind_inlines),
317 --              ("SpecialisedData  ", data_specs),
318 --              ("SpecialisedInsts ", inst_specs),
319                 ("SpecialisedMeths ", method_specs),
320                 ("SpecialisedBinds ", bind_specs)
321                ])
322   where
323     pp_val (str, 0) = empty
324     pp_val (str, n) 
325       | not short   = hcat [text str, int n]
326       | otherwise   = hcat [text (trim str), equals, int n, semi]
327     
328     trim ls     = takeWhile (not.isSpace) (dropWhile isSpace ls)
329
330     fixity_ds   = length [() | FixD d <- decls]
331                 -- NB: this omits fixity decls on local bindings and
332                 -- in class decls.  ToDo
333
334     tycl_decls  = [d | TyClD d <- decls]
335     (class_ds, data_ds, newt_ds, type_ds) = countTyClDecls tycl_decls
336
337     inst_decls  = [d | InstD d <- decls]
338     inst_ds     = length inst_decls
339     default_ds  = length [() | DefD _ <- decls]
340     val_decls   = [d | ValD d <- decls]
341
342     real_exports = case exports of { Nothing -> []; Just es -> es }
343     n_exports    = length real_exports
344     export_ms    = length [() | IEModuleContents _ <- real_exports]
345     export_ds    = n_exports - export_ms
346     export_all   = case exports of { Nothing -> 1; other -> 0 }
347
348     (val_bind_ds, fn_bind_ds, bind_tys, bind_specs, bind_inlines)
349         = count_binds (foldr ThenBinds EmptyBinds val_decls)
350
351     (import_no, import_qual, import_as, import_all, import_partial, import_hiding)
352         = foldr add6 (0,0,0,0,0,0) (map import_info imports)
353     (data_constrs, data_derivs)
354         = foldr add2 (0,0) (map data_info tycl_decls)
355     (class_method_ds, default_method_ds)
356         = foldr add2 (0,0) (map class_info tycl_decls)
357     (inst_method_ds, method_specs, method_inlines)
358         = foldr add3 (0,0,0) (map inst_info inst_decls)
359
360
361     count_binds EmptyBinds        = (0,0,0,0,0)
362     count_binds (ThenBinds b1 b2) = count_binds b1 `add5` count_binds b2
363     count_binds (MonoBind b sigs _) = case (count_monobinds b, count_sigs sigs) of
364                                         ((vs,fs),(ts,_,ss,is)) -> (vs,fs,ts,ss,is)
365
366     count_monobinds EmptyMonoBinds                 = (0,0)
367     count_monobinds (AndMonoBinds b1 b2)           = count_monobinds b1 `add2` count_monobinds b2
368     count_monobinds (PatMonoBind (VarPatIn n) r _) = (1,0)
369     count_monobinds (PatMonoBind p r _)            = (0,1)
370     count_monobinds (FunMonoBind f _ m _)          = (0,1)
371
372     count_sigs sigs = foldr add4 (0,0,0,0) (map sig_info sigs)
373
374     sig_info (Sig _ _ _)            = (1,0,0,0)
375     sig_info (ClassOpSig _ _ _ _)   = (0,1,0,0)
376     sig_info (SpecSig _ _ _)        = (0,0,1,0)
377     sig_info (InlineSig _ _ _)      = (0,0,0,1)
378     sig_info (NoInlineSig _ _ _)    = (0,0,0,1)
379     sig_info _                      = (0,0,0,0)
380
381     import_info (ImportDecl _ _ qual as spec _)
382         = add6 (1, qual_info qual, as_info as, 0,0,0) (spec_info spec)
383     qual_info False  = 0
384     qual_info True   = 1
385     as_info Nothing  = 0
386     as_info (Just _) = 1
387     spec_info Nothing           = (0,0,0,1,0,0)
388     spec_info (Just (False, _)) = (0,0,0,0,1,0)
389     spec_info (Just (True, _))  = (0,0,0,0,0,1)
390
391     data_info (TyData _ _ _ _ _ nconstrs derivs _ _ _ _)
392         = (nconstrs, case derivs of {Nothing -> 0; Just ds -> length ds})
393     data_info other = (0,0)
394
395     class_info (ClassDecl _ _ _ _ meth_sigs def_meths _ _ _ )
396         = case count_sigs meth_sigs of
397             (_,classops,_,_) ->
398                (classops, addpr (count_monobinds def_meths))
399     class_info other = (0,0)
400
401     inst_info (InstDecl _ inst_meths inst_sigs _ _)
402         = case count_sigs inst_sigs of
403             (_,_,ss,is) ->
404                (addpr (count_monobinds inst_meths), ss, is)
405
406     addpr :: (Int,Int) -> Int
407     add1  :: Int -> Int -> Int
408     add2  :: (Int,Int) -> (Int,Int) -> (Int, Int)
409     add3  :: (Int,Int,Int) -> (Int,Int,Int) -> (Int, Int, Int)
410     add4  :: (Int,Int,Int,Int) -> (Int,Int,Int,Int) -> (Int, Int, Int, Int)
411     add5  :: (Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int)
412     add6  :: (Int,Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int, Int)
413
414     addpr (x,y) = x+y
415     add1 x1 y1  = x1+y1
416     add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
417     add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
418     add4 (x1,x2,x3,x4) (y1,y2,y3,y4) = (x1+y1,x2+y2,x3+y3,x4+y4)
419     add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
420     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)
421 \end{code}
422
423 \begin{code}
424 \end{code}
425
426 \begin{code}
427 reportCompile :: ModuleName -> String -> IO ()
428 #if REPORT_TO_MOTHERLODE && __GLASGOW_HASKELL__ >= 303
429 reportCompile mod_name info
430   | not opt_ReportCompile = return ()
431   | otherwise = (do 
432       sock <- udpSocket 0
433       addr <- motherShip
434       sendTo sock (moduleNameUserString mod_name ++ ';': compiler_version ++ 
435                    ';': os ++ ';':arch ++ '\n':' ':info ++ "\n") addr
436       return ()) `catch` (\ _ -> return ())
437
438 motherShip :: IO SockAddr
439 motherShip = do
440   he <- getHostByName "laysan.dcs.gla.ac.uk"
441   case (hostAddresses he) of
442     []    -> IOERROR (userError "No address!")
443     (x:_) -> return (SockAddrInet motherShipPort x)
444
445 --magick
446 motherShipPort :: PortNumber
447 motherShipPort = mkPortNumber 12345
448
449 -- creates a socket capable of sending datagrams,
450 -- binding it to a port
451 --  ( 0 => have the system pick next available port no.)
452 udpSocket :: Int -> IO Socket
453 udpSocket p = do
454   pr <- getProtocolNumber "udp"
455   s  <- socket AF_INET Datagram pr
456   bindSocket s (SockAddrInet (mkPortNumber p) iNADDR_ANY)
457   return s
458 #else
459 reportCompile _ _ = return ()
460 #endif
461
462 \end{code}