[project @ 2000-11-20 14:48:52 by simonpj]
[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, mkModuleInThisPackage )
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      ( stgBindsToInterpSyn, UnlinkedIExpr, UnlinkedIBind, ItblEnv )
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    = HscOK   ModDetails              -- new details (HomeSymbolTable additions)
80              (Maybe ModIface)        -- new iface (if any compilation was done)
81              (Maybe String)          -- generated stub_h filename (in /tmp)
82              (Maybe String)          -- generated stub_c filename (in /tmp)
83              (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
84              PersistentCompilerState -- updated PCS
85
86    | HscFail PersistentCompilerState -- updated PCS
87         -- no errors or warnings; the individual passes
88         -- (parse/rename/typecheck) print messages themselves
89
90 hscMain
91   :: GhciMode
92   -> DynFlags
93   -> Bool                       -- source unchanged?
94   -> ModuleLocation             -- location info
95   -> Maybe ModIface             -- old interface, if available
96   -> HomeSymbolTable            -- for home module ModDetails
97   -> HomeIfaceTable
98   -> PersistentCompilerState    -- IN: persistent compiler state
99   -> IO HscResult
100
101 hscMain ghci_mode dflags source_unchanged location maybe_old_iface hst hit pcs
102  = do {
103       showPass dflags ("Checking old interface for hs = " 
104                         ++ show (ml_hs_file location)
105                         ++ ", hspp = " ++ show (ml_hspp_file location));
106
107       (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
108          <- checkOldIface dflags hit hst pcs 
109                 (unJust "hscMain" (ml_hi_file location))
110                 source_unchanged maybe_old_iface;
111
112       if errs_found then
113          return (HscFail pcs_ch)
114       else do {
115
116       let no_old_iface = not (isJust maybe_checked_iface)
117           what_next | recomp_reqd || no_old_iface = hscRecomp 
118                     | otherwise                   = hscNoRecomp
119       ;
120       what_next ghci_mode dflags location maybe_checked_iface
121                 hst hit pcs_ch
122       }}
123
124
125 -- we definitely expect to have the old interface available
126 hscNoRecomp ghci_mode dflags location (Just old_iface) hst hit pcs_ch
127  | ghci_mode == OneShot
128  = return (HscOK
129            (panic "hscNoRecomp:OneShot") -- no details
130            Nothing -- makes run_phase Hsc stop
131            Nothing Nothing -- foreign export stuff
132            Nothing -- ibinds
133            pcs_ch)
134  | otherwise
135  = do {
136       hPutStrLn stderr "COMPILATION NOT REQUIRED";
137       ;
138       -- CLOSURE
139       (pcs_cl, closure_errs, cl_hs_decls) 
140          <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
141       if closure_errs then 
142          return (HscFail pcs_cl) 
143       else do {
144
145       -- TYPECHECK
146       maybe_tc_result <- typecheckModule dflags pcs_cl hst 
147                                          old_iface alwaysQualify cl_hs_decls;
148       case maybe_tc_result of {
149          Nothing -> return (HscFail pcs_cl);
150          Just (pcs_tc, tc_result) -> do {
151
152       let env_tc      = tc_env tc_result
153           local_insts = tc_insts tc_result
154           local_rules = tc_rules tc_result
155       ;
156       -- create a new details from the closed, typechecked, old iface
157       let new_details = mkModDetailsFromIface env_tc local_insts local_rules
158       ;
159       return (HscOK new_details
160                     Nothing -- tells CM to use old iface and linkables
161                     Nothing Nothing -- foreign export stuff
162                     Nothing -- ibinds
163                     pcs_tc)
164       }}}}
165
166
167 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
168  = do   {
169         ; hPutStrLn stderr "COMPILATION IS REQUIRED";
170
171           -- what target are we shooting for?
172         ; let toInterp = dopt_HscLang dflags == HscInterpreted
173
174             -------------------
175             -- PARSE
176             -------------------
177         ; maybe_parsed <- myParseModule dflags 
178                              (unJust "hscRecomp:hspp" (ml_hspp_file location))
179         ; case maybe_parsed of {
180              Nothing -> return (HscFail pcs_ch);
181              Just rdr_module -> do {
182         ; let this_mod = mkModuleInThisPackage (hsModuleName rdr_module)
183     
184             -------------------
185             -- RENAME
186             -------------------
187         ; showPass dflags "Rename"
188         ; (pcs_rn, maybe_rn_result) 
189              <- renameModule dflags hit hst pcs_ch this_mod rdr_module
190         ; case maybe_rn_result of {
191              Nothing -> return (HscFail pcs_rn);
192              Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
193     
194             -------------------
195             -- TYPECHECK
196             -------------------
197         ; showPass dflags "Typecheck"
198         ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface 
199                                              print_unqualified rn_hs_decls
200         ; case maybe_tc_result of {
201              Nothing -> do { hPutStrLn stderr "Typecheck failed" 
202                            ; return (HscFail pcs_rn) } ;
203              Just (pcs_tc, tc_result) -> do {
204     
205         ; let env_tc        = tc_env tc_result
206               local_insts   = tc_insts tc_result
207
208             -------------------
209             -- DESUGAR, SIMPLIFY, TIDY-CORE
210             -------------------
211           -- We grab the the unfoldings at this point.
212         ; simpl_result <- dsThenSimplThenTidy dflags pcs_tc hst this_mod 
213                                               print_unqualified is_exported tc_result
214         ; let (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
215             
216             -------------------
217             -- CONVERT TO STG
218             -------------------
219         ; (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids) 
220              <- myCoreToStg dflags this_mod tidy_binds
221
222
223             -------------------
224             -- BUILD THE NEW ModDetails AND ModIface
225             -------------------
226         ; let new_details = mkModDetails env_tc local_insts tidy_binds 
227                                          top_level_ids orphan_rules
228         ; final_iface <- mkFinalIface ghci_mode dflags location 
229                                       maybe_checked_iface new_iface new_details
230
231             -------------------
232             -- COMPLETE CODE GENERATION
233             -------------------
234         ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
235              <- restOfCodeGeneration dflags toInterp this_mod
236                    (map ideclName (hsModuleImports rdr_module))
237                    cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
238                    hit (pcs_PIT pcs_tc)       
239
240           -- and the answer is ...
241         ; return (HscOK new_details (Just final_iface)
242                         maybe_stub_h_filename maybe_stub_c_filename
243                         maybe_ibinds pcs_tc)
244           }}}}}}}
245
246
247
248 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
249  = case completeIface maybe_old_iface new_iface new_details of
250       (new_iface, Nothing) -- no change in the interfacfe
251          -> do when (dopt Opt_D_dump_hi_diffs dflags)
252                     (printDump (text "INTERFACE UNCHANGED"))
253                dumpIfSet_dyn dflags Opt_D_dump_hi
254                              "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
255                return new_iface
256       (new_iface, Just sdoc_diffs)
257          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" 
258                                     sdoc_diffs
259                dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" 
260                                     (pprIface new_iface)
261                -- Write the interface file
262                when (ghci_mode /= Interactive) 
263                     (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
264                                 new_iface)
265                return new_iface
266
267
268 myParseModule dflags src_filename
269  = do --------------------------  Parser  ----------------
270       showPass dflags "Parser"
271       -- _scc_     "Parser"
272
273       buf <- hGetStringBuffer True{-expand tabs-} src_filename
274
275       let glaexts | dopt Opt_GlasgowExts dflags = 1#
276                   | otherwise                 = 0#
277
278       case parse buf PState{ bol = 0#, atbol = 1#,
279                              context = [], glasgow_exts = glaexts,
280                              loc = mkSrcLoc (_PK_ src_filename) 1 } of {
281
282         PFailed err -> do { hPutStrLn stderr (showSDoc err);
283                             return Nothing };
284
285         POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
286
287       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
288       
289       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
290                            (ppSourceStats False rdr_module) ;
291       
292       return (Just rdr_module)
293       }}
294
295
296 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info 
297                      foreign_stuff env_tc stg_binds oa_tidy_binds
298                      hit pit -- these last two for mapping ModNames to Modules
299  | toInterp
300  = do (ibinds,itbl_env) 
301          <- stgBindsToInterpSyn dflags (map fst stg_binds) 
302                 local_tycons local_classes
303       return (Nothing, Nothing, Just (ibinds,itbl_env))
304
305  | otherwise
306  = do --------------------------  Code generation -------------------------------
307       -- _scc_     "CodeGen"
308       abstractC <- codeGen dflags this_mod imported_modules
309                            cost_centre_info fe_binders
310                            local_tycons stg_binds
311
312       --------------------------  Code output -------------------------------
313       -- _scc_     "CodeOutput"
314       (maybe_stub_h_name, maybe_stub_c_name)
315          <- codeOutput dflags this_mod local_tycons
316                        oa_tidy_binds stg_binds
317                        c_code h_code abstractC
318
319       return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
320  where
321     local_tycons     = typeEnvTyCons env_tc
322     local_classes    = typeEnvClasses env_tc
323     imported_modules = map mod_name_to_Module imported_module_names
324     (fe_binders,h_code,c_code) = foreign_stuff
325
326     mod_name_to_Module :: ModuleName -> Module
327     mod_name_to_Module nm
328        = let str_mi = case lookupModuleEnvByName hit nm of
329                           Just mi -> mi
330                           Nothing -> case lookupModuleEnvByName pit nm of
331                                         Just mi -> mi
332                                         Nothing -> barf nm
333          in  mi_module str_mi
334     barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for" 
335                        (ppr nm)
336
337
338 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
339  = do --------------------------  Desugaring ----------------
340       showPass dflags "DeSugar"
341       -- _scc_     "DeSugar"
342       (desugared, rules, h_code, c_code, fe_binders) 
343          <- deSugar dflags pcs hst this_mod print_unqual tc_result
344
345       --------------------------  Main Core-language transformations ----------------
346       -- _scc_     "Core2Core"
347       (simplified, orphan_rules) 
348          <- core2core dflags pcs hst is_exported desugared rules
349
350       -- Do the final tidy-up
351       showPass dflags "TidyCore"
352       (tidy_binds, tidy_orphan_rules) 
353          <- tidyCorePgm dflags this_mod simplified orphan_rules
354       
355       return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
356
357
358 myCoreToStg dflags this_mod tidy_binds
359  = do 
360       st_uniqs  <- mkSplitUniqSupply 'g'
361       let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
362
363       () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
364       -- TEMP: the above call zaps some space usage allocated by the
365       -- simplifier, which for reasons I don't understand, persists
366       -- thoroughout code generation
367
368       -- _scc_     "Core2Stg"
369       stg_binds <- topCoreBindsToStg dflags occ_anal_tidy_binds
370
371       showPass dflags "Stg2Stg"
372       -- _scc_     "Stg2Stg"
373       (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
374       let final_ids = collectFinalStgBinders (map fst stg_binds2)
375
376       return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
377 \end{code}
378
379
380 %************************************************************************
381 %*                                                                      *
382 \subsection{Compiling an expression}
383 %*                                                                      *
384 %************************************************************************
385
386 \begin{code}
387 hscExpr
388   :: DynFlags
389   -> HomeSymbolTable    
390   -> HomeIfaceTable
391   -> PersistentCompilerState    -- IN: persistent compiler state
392   -> Module                     -- Context for compiling
393   -> String                     -- The expression
394   -> IO ( PersistentCompilerState, Maybe UnlinkedIExpr )
395
396 #ifndef GHCI
397 hscExpr dflags hst hit pcs this_module expr
398   = panic "hscExpr: non-interactive build"
399 #else 
400
401 hscExpr dflags hst hit pcs0 this_module expr
402   = do  {       -- Parse it
403         maybe_parsed <- hscParseExpr dflags expr;
404         case maybe_parsed of
405              Nothing -> return (pcs0, Nothing)
406              Just parsed_expr -> do {
407
408                 -- Rename it
409         (pcs1, maybe_renamed_expr) <- 
410                 renameExpr dflags hit hst pcs0 this_module parsed_expr;
411         case maybe_renamed_expr of
412                 Nothing -> return (pcs1, Nothing)
413                 Just (print_unqual, rn_expr) -> do {
414
415                 -- Typecheck it
416         maybe_tc_expr <- typecheckExpr dflags pcs1 hst print_unqual this_module rn_expr;
417         case maybe_tc_expr of
418                 Nothing -> return (pcs1, Nothing)
419                 Just tc_expr -> do {
420
421                 -- Desugar it
422         ds_expr <- deSugarExpr dflags pcs1 hst this_module 
423                         print_unqual tc_expr;
424         
425                 -- Simplify it
426         simpl_expr <- simplifyExpr dflags pcs1 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 (pcs1, 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}