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