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