[project @ 2000-11-17 10:13:21 by sewardj]
[ghc-hetmet.git] / ghc / compiler / main / HscMain.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
3 %
4 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
5
6 \begin{code}
7 module HscMain ( HscResult(..), hscMain, 
8                  initPersistentCompilerState ) where
9
10 #include "HsVersions.h"
11
12 import Maybe            ( isJust )
13 import IO               ( hPutStrLn, stderr )
14 import HsSyn
15
16 import StringBuffer     ( hGetStringBuffer )
17 import Parser
18 import Lex              ( PState(..), ParseResult(..) )
19 import SrcLoc           ( mkSrcLoc )
20
21 import Rename           ( renameModule, checkOldIface, closeIfaceDecls )
22 import Rules            ( emptyRuleBase )
23 import PrelInfo         ( wiredInThingEnv, wiredInThings )
24 import PrelNames        ( knownKeyNames )
25 import MkIface          ( completeIface, mkModDetailsFromIface, mkModDetails,
26                           writeIface, pprIface )
27 import TcModule         ( TcResults(..), typecheckModule )
28 import InstEnv          ( emptyInstEnv )
29 import Desugar          ( deSugar )
30 import SimplCore        ( core2core )
31 import OccurAnal        ( occurAnalyseBinds )
32 import CoreUtils        ( coreBindsSize )
33 import CoreTidy         ( tidyCorePgm )
34 import CoreToStg        ( topCoreBindsToStg )
35 import StgSyn           ( collectFinalStgBinders )
36 import SimplStg         ( stg2stg )
37 import CodeGen          ( codeGen )
38 import CodeOutput       ( codeOutput )
39
40 import Module           ( ModuleName, moduleName, mkModuleInThisPackage )
41 import CmdLineOpts
42 import ErrUtils         ( dumpIfSet_dyn, showPass )
43 import Util             ( unJust )
44 import UniqSupply       ( mkSplitUniqSupply )
45
46 import Bag              ( emptyBag )
47 import Outputable
48 import Interpreter      ( UnlinkedIBind, ItblEnv, stgToInterpSyn )
49 import CmStaticInfo     ( GhciMode(..) )
50 import HscStats         ( ppSourceStats )
51 import HscTypes         ( ModDetails, ModIface(..), PersistentCompilerState(..),
52                           PersistentRenamerState(..), ModuleLocation(..),
53                           HomeSymbolTable, 
54                           OrigNameEnv(..), PackageRuleBase, HomeIfaceTable, 
55                           typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
56 import FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
57 import OccName          ( OccName )
58 import Name             ( Name, nameModule, nameOccName, getName  )
59 import Name             ( emptyNameEnv )
60 import Module           ( Module, lookupModuleEnvByName )
61
62 import Monad            ( when )
63 \end{code}
64
65
66 %************************************************************************
67 %*                                                                      *
68 \subsection{The main compiler pipeline}
69 %*                                                                      *
70 %************************************************************************
71
72 \begin{code}
73 data HscResult
74    = HscOK   ModDetails              -- new details (HomeSymbolTable additions)
75              (Maybe ModIface)        -- new iface (if any compilation was done)
76              (Maybe String)          -- generated stub_h filename (in /tmp)
77              (Maybe String)          -- generated stub_c filename (in /tmp)
78              (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
79              PersistentCompilerState -- updated PCS
80
81    | HscFail PersistentCompilerState -- updated PCS
82         -- no errors or warnings; the individual passes
83         -- (parse/rename/typecheck) print messages themselves
84
85 hscMain
86   :: GhciMode
87   -> DynFlags
88   -> Bool                       -- source unchanged?
89   -> ModuleLocation             -- location info
90   -> Maybe ModIface             -- old interface, if available
91   -> HomeSymbolTable            -- for home module ModDetails
92   -> HomeIfaceTable
93   -> PersistentCompilerState    -- IN: persistent compiler state
94   -> IO HscResult
95
96 hscMain ghci_mode dflags source_unchanged location maybe_old_iface hst hit pcs
97  = do {
98       putStrLn ("CHECKING OLD IFACE for hs = " ++ show (ml_hs_file location)
99                 ++ ", hspp = " ++ show (ml_hspp_file location));
100
101       (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
102          <- checkOldIface dflags hit hst pcs (unJust (ml_hi_file location) "hscMain")
103                           source_unchanged maybe_old_iface;
104
105       if errs_found then
106          return (HscFail pcs_ch)
107       else do {
108
109       let no_old_iface = not (isJust maybe_checked_iface)
110           what_next | recomp_reqd || no_old_iface = hscRecomp 
111                     | otherwise                   = hscNoRecomp
112       ;
113       what_next ghci_mode dflags location maybe_checked_iface
114                 hst hit pcs_ch
115       }}
116
117
118 -- we definitely expect to have the old interface available
119 hscNoRecomp ghci_mode dflags location (Just old_iface) hst hit pcs_ch
120  | ghci_mode == OneShot
121  = return (HscOK
122            (panic "hscNoRecomp:OneShot") -- no details
123            Nothing -- makes run_phase Hsc stop
124            Nothing Nothing -- foreign export stuff
125            Nothing -- ibinds
126            pcs_ch)
127  | otherwise
128  = do {
129       hPutStrLn stderr "COMPILATION NOT REQUIRED";
130       let this_mod = mi_module old_iface
131       ;
132       -- CLOSURE
133       (pcs_cl, closure_errs, cl_hs_decls) 
134          <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
135       if closure_errs then 
136          return (HscFail pcs_cl) 
137       else do {
138
139       -- TYPECHECK
140       maybe_tc_result <- typecheckModule dflags pcs_cl hst 
141                                          old_iface alwaysQualify cl_hs_decls;
142       case maybe_tc_result of {
143          Nothing -> return (HscFail pcs_cl);
144          Just (pcs_tc, tc_result) -> do {
145
146       let env_tc      = tc_env tc_result
147           local_insts = tc_insts tc_result
148           local_rules = tc_rules tc_result
149       ;
150       -- create a new details from the closed, typechecked, old iface
151       let new_details = mkModDetailsFromIface env_tc local_insts local_rules
152       ;
153       return (HscOK new_details
154                     Nothing -- tells CM to use old iface and linkables
155                     Nothing Nothing -- foreign export stuff
156                     Nothing -- ibinds
157                     pcs_tc)
158       }}}}
159
160
161 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
162  = do   {
163         ; hPutStrLn stderr "COMPILATION IS REQUIRED";
164
165           -- what target are we shooting for?
166         ; let toInterp = dopt_HscLang dflags == HscInterpreted
167
168             -------------------
169             -- PARSE
170             -------------------
171         ; maybe_parsed <- myParseModule dflags (unJust (ml_hspp_file location) 
172                                                        "hscRecomp:hspp")
173         ; case maybe_parsed of {
174              Nothing -> return (HscFail pcs_ch);
175              Just rdr_module -> do {
176         ; let this_mod = mkModuleInThisPackage (hsModuleName rdr_module)
177     
178             -------------------
179             -- RENAME
180             -------------------
181         ; (pcs_rn, maybe_rn_result) 
182              <- renameModule dflags hit hst pcs_ch this_mod rdr_module
183         ; case maybe_rn_result of {
184              Nothing -> return (HscFail pcs_rn);
185              Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
186     
187             -------------------
188             -- TYPECHECK
189             -------------------
190         ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface 
191                                              print_unqualified rn_hs_decls
192         ; case maybe_tc_result of {
193              Nothing -> do { hPutStrLn stderr "Typecheck failed" 
194                            ; return (HscFail pcs_rn) } ;
195              Just (pcs_tc, tc_result) -> do {
196     
197         ; let env_tc        = tc_env tc_result
198               local_insts   = tc_insts tc_result
199
200             -------------------
201             -- DESUGAR, SIMPLIFY, TIDY-CORE
202             -------------------
203           -- We grab the the unfoldings at this point.
204         ; simpl_result <- dsThenSimplThenTidy dflags pcs_tc hst this_mod 
205                                               print_unqualified is_exported tc_result
206         ; let (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
207             
208             -------------------
209             -- CONVERT TO STG
210             -------------------
211         ; (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids) 
212              <- myCoreToStg dflags this_mod tidy_binds
213
214
215             -------------------
216             -- BUILD THE NEW ModDetails AND ModIface
217             -------------------
218         ; let new_details = mkModDetails env_tc local_insts tidy_binds 
219                                          top_level_ids orphan_rules
220         ; final_iface <- mkFinalIface dflags location maybe_checked_iface 
221                                       new_iface new_details
222
223             -------------------
224             -- COMPLETE CODE GENERATION
225             -------------------
226         ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
227              <- restOfCodeGeneration dflags toInterp this_mod
228                    (map ideclName (hsModuleImports rdr_module))
229                    cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
230                    hit (pcs_PIT pcs_tc)       
231
232           -- and the answer is ...
233         ; return (HscOK new_details (Just final_iface)
234                         maybe_stub_h_filename maybe_stub_c_filename
235                         maybe_ibinds pcs_tc)
236           }}}}}}}
237
238
239
240 mkFinalIface dflags location maybe_old_iface new_iface new_details
241  = case completeIface maybe_old_iface new_iface new_details of
242       (new_iface, Nothing) -- no change in the interfacfe
243          -> do when (dopt Opt_D_dump_hi_diffs dflags)
244                     (printDump (text "INTERFACE UNCHANGED"))
245                dumpIfSet_dyn dflags Opt_D_dump_hi
246                              "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
247                return new_iface
248       (new_iface, Just sdoc_diffs)
249          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
250                dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
251                -- Write the interface file
252                writeIface (unJust (ml_hi_file location) "hscRecomp:hi") new_iface
253                return new_iface
254
255
256 myParseModule dflags src_filename
257  = do --------------------------  Parser  ----------------
258       showPass dflags "Parser"
259       -- _scc_     "Parser"
260
261       buf <- hGetStringBuffer True{-expand tabs-} src_filename
262
263       let glaexts | dopt Opt_GlasgowExts dflags = 1#
264                   | otherwise                 = 0#
265
266       case parse buf PState{ bol = 0#, atbol = 1#,
267                              context = [], glasgow_exts = glaexts,
268                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
269
270         PFailed err -> do { hPutStrLn stderr (showSDoc err);
271                             return Nothing };
272
273         POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
274
275       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
276       
277       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
278                            (ppSourceStats False rdr_module) ;
279       
280       return (Just rdr_module)
281       }}
282
283
284 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info 
285                      foreign_stuff env_tc stg_binds oa_tidy_binds
286                      hit pit -- these last two for mapping ModNames to Modules
287  | toInterp
288  = do (ibinds,itbl_env) 
289          <- stgToInterpSyn (map fst stg_binds) local_tycons local_classes
290       return (Nothing, Nothing, Just (ibinds,itbl_env))
291
292  | otherwise
293  = do --------------------------  Code generation -------------------------------
294       -- _scc_     "CodeGen"
295       abstractC <- codeGen dflags this_mod imported_modules
296                            cost_centre_info fe_binders
297                            local_tycons stg_binds
298
299       --------------------------  Code output -------------------------------
300       -- _scc_     "CodeOutput"
301       (maybe_stub_h_name, maybe_stub_c_name)
302          <- codeOutput dflags this_mod local_tycons
303                        oa_tidy_binds stg_binds
304                        c_code h_code abstractC
305
306       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
307  where
308     local_tycons     = typeEnvTyCons env_tc
309     local_classes    = typeEnvClasses env_tc
310     imported_modules = map mod_name_to_Module imported_module_names
311     (fe_binders,h_code,c_code) = foreign_stuff
312
313     mod_name_to_Module :: ModuleName -> Module
314     mod_name_to_Module nm
315        = let str_mi = case lookupModuleEnvByName hit nm of
316                           Just mi -> mi
317                           Nothing -> case lookupModuleEnvByName pit nm of
318                                         Just mi -> mi
319                                         Nothing -> barf nm
320          in  mi_module str_mi
321     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
322                        (ppr nm)
323
324
325 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
326  = do --------------------------  Desugaring ----------------
327       -- _scc_     "DeSugar"
328       (desugared, rules, h_code, c_code, fe_binders) 
329          <- deSugar dflags pcs hst this_mod print_unqual tc_result
330
331       --------------------------  Main Core-language transformations ----------------
332       -- _scc_     "Core2Core"
333       (simplified, orphan_rules) 
334          <- core2core dflags pcs hst is_exported desugared rules
335
336       -- Do the final tidy-up
337       (tidy_binds, tidy_orphan_rules) 
338          <- tidyCorePgm dflags this_mod simplified orphan_rules
339       
340       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
341
342
343 myCoreToStg dflags this_mod tidy_binds
344  = do 
345       c2s_uniqs <- mkSplitUniqSupply 'c'
346       st_uniqs  <- mkSplitUniqSupply 'g'
347       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
348
349       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
350       -- TEMP: the above call zaps some space usage allocated by the
351       -- simplifier, which for reasons I don't understand, persists
352       -- thoroughout code generation
353
354       showPass dflags "Core2Stg"
355       -- _scc_     "Core2Stg"
356       let stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
357
358       showPass dflags "Stg2Stg"
359       -- _scc_     "Stg2Stg"
360       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
361       let final_ids = collectFinalStgBinders (map fst stg_binds2)
362
363       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
364 \end{code}
365
366
367 %************************************************************************
368 %*                                                                      *
369 \subsection{Compiling an expression}
370 %*                                                                      *
371 %************************************************************************
372
373 hscExpr
374   :: DynFlags
375   -> HomeSymbolTable    
376   -> HomeIfaceTable
377   -> PersistentCompilerState    -- IN: persistent compiler state
378   -> Module                     -- Context for compiling
379   -> String                     -- The expression
380   -> IO HscResult
381
382 hscExpr dflags hst hit pcs this_module expr
383   = do  {       -- Parse it
384           maybe_parsed <- myParseExpr dflags expr
385         ; case maybe_parsed of {
386              Nothing -> return (HscFail pcs_ch);
387              Just parsed_expr -> do {
388
389                 -- Rename it
390           (new_pcs, maybe_renamed_expr) <- renameExpr dflags hit hst pcs this_module parsed_expr ;
391         ; case maybe_renamed_expr of {
392                 Nothing -> FAIL
393                 Just (print_unqual, rn_expr) -> 
394
395                 -- Typecheck it
396           maybe_tc_expr <- typecheckExpr dflags pcs hst print_unqual rn_expr 
397         ; case maybe_tc_expr of
398                 Nothing -> FAIL
399                 Just tc_expr ->
400
401                 -- Desugar it
402         ; ds_expr <- deSugarExpr dflags pcs hst this_module print_unqual tc_expr
403         
404                 -- Simplify it
405         ; simpl_expr <- simplifyExpr dflags pcs hst ds_expr
406
407         ; return I'M NOT SURE
408         }
409
410         
411
412
413 %************************************************************************
414 %*                                                                      *
415 \subsection{Initial persistent state}
416 %*                                                                      *
417 %************************************************************************
418
419 \begin{code}
420 initPersistentCompilerState :: IO PersistentCompilerState
421 initPersistentCompilerState 
422   = do prs <- initPersistentRenamerState
423        return (
424         PCS { pcs_PIT   = emptyIfaceTable,
425               pcs_PTE   = wiredInThingEnv,
426               pcs_insts = emptyInstEnv,
427               pcs_rules = emptyRuleBase,
428               pcs_PRS   = prs
429             }
430         )
431
432 initPersistentRenamerState :: IO PersistentRenamerState
433   = do ns <- mkSplitUniqSupply 'r'
434        return (
435         PRS { prsOrig  = Orig { origNames  = initOrigNames,
436                                 origIParam = emptyFM },
437               prsDecls = (emptyNameEnv, 0),
438               prsInsts = (emptyBag, 0),
439               prsRules = (emptyBag, 0),
440               prsNS    = ns
441             }
442         )
443
444 initOrigNames :: FiniteMap (ModuleName,OccName) Name
445 initOrigNames 
446    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
447      where
448         grab names = foldl add emptyFM names
449         add env name 
450            = addToFM env (moduleName (nameModule name), nameOccName name) name
451
452
453 initRules :: PackageRuleBase
454 initRules = emptyRuleBase
455 {- SHOULD BE (ish)
456             foldl add emptyVarEnv builtinRules
457           where
458             add env (name,rule) 
459               = extendRuleBase env name rule
460 -}
461 \end{code}