[project @ 2000-11-16 16:23:03 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) "hscRecomp:hspp")
172         ; case maybe_parsed of {
173              Nothing -> return (HscFail pcs_ch);
174              Just rdr_module -> do {
175         ; let this_mod = mkModuleInThisPackage (hsModuleName rdr_module)
176     
177             -------------------
178             -- RENAME
179             -------------------
180         ; (pcs_rn, maybe_rn_result) 
181              <- renameModule dflags hit hst pcs_ch this_mod rdr_module
182         ; case maybe_rn_result of {
183              Nothing -> return (HscFail pcs_rn);
184              Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
185     
186             -------------------
187             -- TYPECHECK
188             -------------------
189         ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface 
190                                              print_unqualified rn_hs_decls
191         ; case maybe_tc_result of {
192              Nothing -> do { hPutStrLn stderr "Typecheck failed" 
193                            ; return (HscFail pcs_rn) } ;
194              Just (pcs_tc, tc_result) -> do {
195     
196         ; let env_tc        = tc_env tc_result
197               local_insts   = tc_insts tc_result
198
199             -------------------
200             -- DESUGAR, SIMPLIFY, TIDY-CORE
201             -------------------
202           -- We grab the the unfoldings at this point.
203         ; simpl_result <- dsThenSimplThenTidy dflags pcs_tc hst this_mod 
204                                               print_unqualified is_exported tc_result
205         ; let (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
206             
207             -------------------
208             -- CONVERT TO STG
209             -------------------
210         ; (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids) 
211              <- myCoreToStg dflags this_mod tidy_binds
212
213
214             -------------------
215             -- BUILD THE NEW ModDetails AND ModIface
216             -------------------
217         ; let new_details = mkModDetails env_tc local_insts tidy_binds 
218                                          top_level_ids orphan_rules
219         ; final_iface <- mkFinalIface dflags location maybe_checked_iface 
220                                       new_iface new_details
221
222             -------------------
223             -- COMPLETE CODE GENERATION
224             -------------------
225         ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
226              <- restOfCodeGeneration dflags toInterp this_mod
227                    (map ideclName (hsModuleImports rdr_module))
228                    cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
229                    hit (pcs_PIT pcs_tc)       
230
231           -- and the answer is ...
232         ; return (HscOK new_details (Just final_iface)
233                         maybe_stub_h_filename maybe_stub_c_filename
234                         maybe_ibinds pcs_tc)
235           }}}}}}}
236
237
238
239 mkFinalIface dflags location maybe_old_iface new_iface new_details
240  = case completeIface maybe_old_iface new_iface new_details of
241       (new_iface, Nothing) -- no change in the interfacfe
242          -> do when (dopt Opt_D_dump_hi_diffs dflags)
243                     (printDump (text "INTERFACE UNCHANGED"))
244                dumpIfSet_dyn dflags Opt_D_dump_hi
245                              "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
246                return new_iface
247       (new_iface, Just sdoc_diffs)
248          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
249                dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
250                -- Write the interface file
251                writeIface (unJust (ml_hi_file location) "hscRecomp:hi") new_iface
252                return new_iface
253
254
255 myParseModule dflags src_filename
256  = do --------------------------  Parser  ----------------
257       showPass dflags "Parser"
258       -- _scc_     "Parser"
259
260       buf <- hGetStringBuffer True{-expand tabs-} src_filename
261
262       let glaexts | dopt Opt_GlasgowExts dflags = 1#
263                   | otherwise                 = 0#
264
265       case parse buf PState{ bol = 0#, atbol = 1#,
266                              context = [], glasgow_exts = glaexts,
267                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
268
269         PFailed err -> do { hPutStrLn stderr (showSDoc err);
270                             return Nothing };
271
272         POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
273
274       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
275       
276       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
277                            (ppSourceStats False rdr_module) ;
278       
279       return (Just rdr_module)
280       }}
281
282
283 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info 
284                      foreign_stuff env_tc stg_binds oa_tidy_binds
285                      hit pit -- these last two for mapping ModNames to Modules
286  | toInterp
287  = do (ibinds,itbl_env) 
288          <- stgToInterpSyn (map fst stg_binds) local_tycons local_classes
289       return (Nothing, Nothing, Just (ibinds,itbl_env))
290
291  | otherwise
292  = do --------------------------  Code generation -------------------------------
293       -- _scc_     "CodeGen"
294       abstractC <- codeGen dflags this_mod imported_modules
295                            cost_centre_info fe_binders
296                            local_tycons stg_binds
297
298       --------------------------  Code output -------------------------------
299       -- _scc_     "CodeOutput"
300       (maybe_stub_h_name, maybe_stub_c_name)
301          <- codeOutput dflags this_mod local_tycons
302                        oa_tidy_binds stg_binds
303                        c_code h_code abstractC
304
305       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
306  where
307     local_tycons     = typeEnvTyCons env_tc
308     local_classes    = typeEnvClasses env_tc
309     imported_modules = map mod_name_to_Module imported_module_names
310     (fe_binders,h_code,c_code) = foreign_stuff
311
312     mod_name_to_Module :: ModuleName -> Module
313     mod_name_to_Module nm
314        = let str_mi = case lookupModuleEnvByName hit nm of
315                           Just mi -> mi
316                           Nothing -> case lookupModuleEnvByName pit nm of
317                                         Just mi -> mi
318                                         Nothing -> barf nm
319          in  mi_module str_mi
320     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
321                        (ppr nm)
322
323
324 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
325  = do --------------------------  Desugaring ----------------
326       -- _scc_     "DeSugar"
327       (desugared, rules, h_code, c_code, fe_binders) 
328          <- deSugar dflags pcs hst this_mod print_unqual tc_result
329
330       --------------------------  Main Core-language transformations ----------------
331       -- _scc_     "Core2Core"
332       (simplified, orphan_rules) 
333          <- core2core dflags pcs hst is_exported desugared rules
334
335       -- Do the final tidy-up
336       (tidy_binds, tidy_orphan_rules) 
337          <- tidyCorePgm dflags this_mod simplified orphan_rules
338       
339       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
340
341
342 myCoreToStg dflags this_mod tidy_binds
343  = do 
344       c2s_uniqs <- mkSplitUniqSupply 'c'
345       st_uniqs  <- mkSplitUniqSupply 'g'
346       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
347
348       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
349       -- TEMP: the above call zaps some space usage allocated by the
350       -- simplifier, which for reasons I don't understand, persists
351       -- thoroughout code generation
352
353       showPass dflags "Core2Stg"
354       -- _scc_     "Core2Stg"
355       let stg_binds   = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
356
357       showPass dflags "Stg2Stg"
358       -- _scc_     "Stg2Stg"
359       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
360       let final_ids = collectFinalStgBinders (map fst stg_binds2)
361
362       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
363 \end{code}
364
365
366 %************************************************************************
367 %*                                                                      *
368 \subsection{Compiling an expression}
369 %*                                                                      *
370 %************************************************************************
371
372 hscExpr
373   :: DynFlags
374   -> HomeSymbolTable    
375   -> HomeIfaceTable
376   -> PersistentCompilerState    -- IN: persistent compiler state
377   -> Module                     -- Context for compiling
378   -> String                     -- The expression
379   -> IO HscResult
380
381 hscExpr dflags hst hit pcs this_module expr
382   = do  {       -- Parse it
383           maybe_parsed <- myParseExpr dflags expr
384         ; case maybe_parsed of {
385              Nothing -> return (HscFail pcs_ch);
386              Just parsed_expr -> do {
387
388                 -- Rename it
389           (new_pcs, maybe_renamed_expr) <- renameExpr dflags hit hst pcs this_module parsed_expr ;
390         ; case maybe_renamed_expr of {
391                 Nothing -> FAIL
392                 Just (print_unqual, rn_expr) -> 
393
394                 -- Typecheck it
395           maybe_tc_expr <- typecheckExpr dflags pcs hst print_unqual rn_expr 
396         ; case maybe_tc_expr of
397                 Nothing -> FAIL
398                 Just tc_expr ->
399
400                 -- Desugar it
401         ; ds_expr <- deSugarExpr dflags pcs hst this_module print_unqual tc_expr
402         
403                 -- Simplify it
404         ; simpl_expr <- simplifyExpr dflags pcs hst ds_expr
405
406         ; return I'M NOT SURE
407         }
408
409         
410
411
412 %************************************************************************
413 %*                                                                      *
414 \subsection{Initial persistent state}
415 %*                                                                      *
416 %************************************************************************
417
418 \begin{code}
419 initPersistentCompilerState :: IO PersistentCompilerState
420 initPersistentCompilerState 
421   = do prs <- initPersistentRenamerState
422        return (
423         PCS { pcs_PIT   = emptyIfaceTable,
424               pcs_PTE   = wiredInThingEnv,
425               pcs_insts = emptyInstEnv,
426               pcs_rules = emptyRuleBase,
427               pcs_PRS   = prs
428             }
429         )
430
431 initPersistentRenamerState :: IO PersistentRenamerState
432   = do ns <- mkSplitUniqSupply 'r'
433        return (
434         PRS { prsOrig  = Orig { origNames  = initOrigNames,
435                                 origIParam = emptyFM },
436               prsDecls = (emptyNameEnv, 0),
437               prsInsts = (emptyBag, 0),
438               prsRules = (emptyBag, 0),
439               prsNS    = ns
440             }
441         )
442
443 initOrigNames :: FiniteMap (ModuleName,OccName) Name
444 initOrigNames 
445    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
446      where
447         grab names = foldl add emptyFM names
448         add env name 
449            = addToFM env (moduleName (nameModule name), nameOccName name) name
450
451
452 initRules :: PackageRuleBase
453 initRules = emptyRuleBase
454 {- SHOULD BE (ish)
455             foldl add emptyVarEnv builtinRules
456           where
457             add env (name,rule) 
458               = extendRuleBase env name rule
459 -}
460 \end{code}