[project @ 2002-02-06 11:00:58 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / HscMain.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
3 %
4
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
6
7 \begin{code}
8 module HscMain ( HscResult(..), hscMain, 
9 #ifdef GHCI
10                  hscStmt, hscThing, hscModuleContents,
11 #endif
12                  initPersistentCompilerState ) where
13
14 #include "HsVersions.h"
15
16 #ifdef GHCI
17 import Interpreter
18 import ByteCodeGen      ( byteCodeGen )
19 import CoreTidy         ( tidyCoreExpr )
20 import CorePrep         ( corePrepExpr )
21 import Rename           ( renameStmt, renameRdrName, slurpIface )
22 import RdrName          ( rdrNameOcc, setRdrNameOcc )
23 import RdrHsSyn         ( RdrNameStmt )
24 import OccName          ( dataName, tcClsName, 
25                           occNameSpace, setOccNameSpace )
26 import Type             ( Type )
27 import Id               ( Id, idName, setGlobalIdDetails )
28 import IdInfo           ( GlobalIdDetails(VanillaGlobal) )
29 import Name             ( isLocalName )
30 import NameEnv          ( lookupNameEnv )
31 import Module           ( lookupModuleEnv )
32 import RdrName          ( rdrEnvElts )
33 import PrelNames        ( iNTERACTIVE )
34 import StringBuffer     ( stringToStringBuffer )
35 import FastString       ( mkFastString )
36 import Maybes           ( catMaybes )
37
38 import List             ( nub )
39 #endif
40
41 import HsSyn
42
43 import RdrName          ( mkRdrOrig )
44 import Id               ( idName )
45 import IdInfo           ( CafInfo(..), CgInfoEnv, CgInfo(..) )
46 import StringBuffer     ( hGetStringBuffer, freeStringBuffer )
47 import Parser
48 import Lex              ( PState(..), ParseResult(..) )
49 import SrcLoc           ( mkSrcLoc )
50 import Finder           ( findModule )
51 import Rename           ( checkOldIface, renameModule, closeIfaceDecls )
52 import Rules            ( emptyRuleBase )
53 import PrelInfo         ( wiredInThingEnv, wiredInThings )
54 import PrelRules        ( builtinRules )
55 import PrelNames        ( knownKeyNames )
56 import MkIface          ( mkFinalIface )
57 import TcModule
58 import InstEnv          ( emptyInstEnv )
59 import Desugar
60 import SimplCore
61 import CoreUtils        ( coreBindsSize )
62 import CoreTidy         ( tidyCorePgm )
63 import CorePrep         ( corePrepPgm )
64 import StgSyn
65 import CoreToStg        ( coreToStg )
66 import SimplStg         ( stg2stg )
67 import CodeGen          ( codeGen )
68 import CodeOutput       ( codeOutput )
69
70 import Module           ( ModuleName, moduleName, mkHomeModule )
71 import CmdLineOpts
72 import DriverState      ( v_HCHeader )
73 import ErrUtils         ( dumpIfSet_dyn, showPass, printError )
74 import Util             ( unJust )
75 import UniqSupply       ( mkSplitUniqSupply )
76
77 import Bag              ( consBag, emptyBag )
78 import Outputable
79 import HscStats         ( ppSourceStats )
80 import HscTypes
81 import FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
82 import OccName          ( OccName )
83 import Name             ( Name, nameModule, nameOccName, getName, isGlobalName )
84 import NameEnv          ( emptyNameEnv, mkNameEnv )
85 import Module           ( Module )
86
87 import IOExts           ( newIORef, readIORef, writeIORef, 
88                           unsafePerformIO )
89
90 import Monad            ( when )
91 import Maybe            ( isJust, fromJust )
92 import IO
93
94 import MkExternalCore   ( emitExternalCore )
95 \end{code}
96
97
98 %************************************************************************
99 %*                                                                      *
100 \subsection{The main compiler pipeline}
101 %*                                                                      *
102 %************************************************************************
103
104 \begin{code}
105 data HscResult
106    -- compilation failed
107    = HscFail     PersistentCompilerState -- updated PCS
108    -- concluded that it wasn't necessary
109    | HscNoRecomp PersistentCompilerState -- updated PCS
110                  ModDetails              -- new details (HomeSymbolTable additions)
111                  ModIface                -- new iface (if any compilation was done)
112    -- did recompilation
113    | HscRecomp   PersistentCompilerState -- updated PCS
114                  ModDetails              -- new details (HomeSymbolTable additions)
115                  ModIface                -- new iface (if any compilation was done)
116                  Bool                   -- stub_h exists
117                  Bool                   -- stub_c exists
118 #ifdef GHCI
119                  (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
120 #else
121                  (Maybe ())                      -- no interpreted code whatsoever
122 #endif
123
124         -- no errors or warnings; the individual passes
125         -- (parse/rename/typecheck) print messages themselves
126
127 hscMain
128   :: GhciMode
129   -> DynFlags
130   -> Module
131   -> ModuleLocation             -- location info
132   -> Bool                       -- True <=> source unchanged
133   -> Bool                       -- True <=> have an object file (for msgs only)
134   -> Maybe ModIface             -- old interface, if available
135   -> HomeSymbolTable            -- for home module ModDetails
136   -> HomeIfaceTable
137   -> PersistentCompilerState    -- IN: persistent compiler state
138   -> IO HscResult
139
140 hscMain ghci_mode dflags mod location source_unchanged have_object 
141         maybe_old_iface hst hit pcs
142  = {-# SCC "hscMain" #-}
143    do {
144       showPass dflags ("Checking old interface for hs = " 
145                         ++ show (ml_hs_file location)
146                         ++ ", hspp = " ++ show (ml_hspp_file location));
147
148       (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
149          <- _scc_ "checkOldIface"
150             checkOldIface ghci_mode dflags hit hst pcs mod (ml_hi_file location)
151                 source_unchanged maybe_old_iface;
152
153       if errs_found then
154          return (HscFail pcs_ch)
155       else do {
156
157       let no_old_iface = not (isJust maybe_checked_iface)
158           what_next | recomp_reqd || no_old_iface = hscRecomp 
159                     | otherwise                   = hscNoRecomp
160       ;
161       what_next ghci_mode dflags have_object mod location 
162                 maybe_checked_iface hst hit pcs_ch
163       }}
164
165
166 -- we definitely expect to have the old interface available
167 hscNoRecomp ghci_mode dflags have_object 
168             mod location (Just old_iface) hst hit pcs_ch
169  | ghci_mode == OneShot
170  = do {
171       when (verbosity dflags > 0) $
172           hPutStrLn stderr "compilation IS NOT required";
173       let { bomb = panic "hscNoRecomp:OneShot" };
174       return (HscNoRecomp pcs_ch bomb bomb)
175       }
176  | otherwise
177  = do {
178       when (verbosity dflags >= 1) $
179                 hPutStrLn stderr ("Skipping  " ++ 
180                         showModMsg have_object mod location);
181
182       -- CLOSURE
183       (pcs_cl, closure_errs, cl_hs_decls) 
184          <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
185       if closure_errs then 
186          return (HscFail pcs_cl) 
187       else do {
188
189       -- TYPECHECK
190       maybe_tc_result 
191         <- typecheckIface dflags pcs_cl hst old_iface cl_hs_decls;
192
193       case maybe_tc_result of {
194          Nothing -> return (HscFail pcs_cl);
195          Just (pcs_tc, new_details) ->
196
197       return (HscNoRecomp pcs_tc new_details old_iface)
198       }}}
199
200 hscRecomp ghci_mode dflags have_object 
201           mod location maybe_checked_iface hst hit pcs_ch
202  = do   {
203           -- what target are we shooting for?
204         ; let toInterp = dopt_HscLang dflags == HscInterpreted
205         ; let toNothing = dopt_HscLang dflags == HscNothing
206
207         ; when (ghci_mode /= OneShot && verbosity dflags >= 1) $
208                 hPutStrLn stderr ("Compiling " ++ 
209                         showModMsg (not toInterp) mod location);
210
211             -------------------
212             -- PARSE
213             -------------------
214         ; maybe_parsed <- myParseModule dflags 
215                              (unJust "hscRecomp:hspp" (ml_hspp_file location))
216         ; case maybe_parsed of {
217              Nothing -> return (HscFail pcs_ch);
218              Just rdr_module -> do {
219         ; let this_mod = mkHomeModule (hsModuleName rdr_module)
220     
221             -------------------
222             -- RENAME
223             -------------------
224         ; (pcs_rn, print_unqual, maybe_rn_result) 
225              <- _scc_ "Rename" 
226                  renameModule dflags ghci_mode hit hst pcs_ch this_mod rdr_module
227         ; case maybe_rn_result of {
228              Nothing -> return (HscFail pcs_ch);
229              Just (dont_discard, new_iface, rn_result) -> do {
230
231             -------------------
232             -- TYPECHECK
233             -------------------
234         ; maybe_tc_result 
235             <- _scc_ "TypeCheck" 
236                typecheckModule dflags pcs_rn hst print_unqual rn_result
237         ; case maybe_tc_result of {
238              Nothing -> return (HscFail pcs_ch);
239              Just (pcs_tc, tc_result) -> do {
240     
241             -------------------
242             -- DESUGAR
243             -------------------
244         ; (ds_details, foreign_stuff) 
245              <- _scc_ "DeSugar" 
246                 deSugar dflags pcs_tc hst this_mod print_unqual tc_result
247
248         ; pcs_middle
249             <- _scc_ "pcs_middle"
250                 if ghci_mode == OneShot 
251                   then do init_pcs <- initPersistentCompilerState
252                           init_prs <- initPersistentRenamerState
253                           let 
254                               rules   = pcs_rules pcs_tc        
255                               orig_tc = prsOrig (pcs_PRS pcs_tc)
256                               new_prs = init_prs{ prsOrig=orig_tc }
257
258                           orig_tc `seq` rules `seq` new_prs `seq`
259                             return init_pcs{ pcs_PRS = new_prs,
260                                              pcs_rules = rules }
261                   else return pcs_tc
262
263         -- alive at this point:  
264         --      pcs_middle
265         --      foreign_stuff
266         --      ds_details
267         --      new_iface               
268
269             -------------------
270             -- SIMPLIFY
271             -------------------
272         ; simpl_details
273              <- _scc_     "Core2Core"
274                 core2core dflags pcs_middle hst dont_discard ds_details
275
276             -------------------
277             -- TIDY
278             -------------------
279         ; cg_info_ref <- newIORef Nothing ;
280         ; let cg_info :: CgInfoEnv
281               cg_info = unsafePerformIO $ do {
282                            maybe_cg_env <- readIORef cg_info_ref ;
283                            case maybe_cg_env of
284                              Just env -> return env
285                              Nothing  -> do { printError "Urk! Looked at CgInfo too early!";
286                                               return emptyNameEnv } }
287                 -- cg_info_ref will be filled in just after restOfCodeGeneration
288                 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
289
290         ; (pcs_simpl, tidy_details) 
291              <- _scc_ "CoreTidy"
292                 tidyCorePgm dflags this_mod pcs_middle cg_info simpl_details
293       
294         ; pcs_final <- if ghci_mode == OneShot then initPersistentCompilerState
295                                                else return pcs_simpl
296
297         -- alive at this point:  
298         --      tidy_details
299         --      new_iface               
300
301         ; emitExternalCore dflags new_iface tidy_details 
302
303         ; let final_details = tidy_details {md_binds = []} 
304         ; final_details `seq` return ()
305
306             -------------------
307             -- PREPARE FOR CODE GENERATION
308             -------------------
309               -- Do saturation and convert to A-normal form
310         ; prepd_details <- _scc_ "CorePrep" 
311                            corePrepPgm dflags tidy_details
312
313             -------------------
314             -- CONVERT TO STG and COMPLETE CODE GENERATION
315             -------------------
316         ; let
317             ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
318
319             local_tycons     = typeEnvTyCons  env_tc
320             local_classes    = typeEnvClasses env_tc
321
322             imported_module_names = map ideclName (hsModuleImports rdr_module)
323
324             mod_name_to_Module nm
325                  = do m <- findModule nm ; return (fst (fromJust m))
326
327             (h_code, c_code, headers, fe_binders) = foreign_stuff
328
329             -- turn the list of headers requested in foreign import
330             -- declarations into a string suitable for emission into generated
331             -- C code...
332             --
333             foreign_headers =   
334                 unlines 
335               . map (\fname -> "#include \"" ++ _UNPK_ fname ++ "\"")
336               . reverse 
337               $ headers
338
339           -- ...and add the string to the headers requested via command line
340           -- options 
341           --
342         ; fhdrs <- readIORef v_HCHeader
343         ; writeIORef v_HCHeader (fhdrs ++ foreign_headers)
344
345         ; imported_modules <- mapM mod_name_to_Module imported_module_names
346
347         ; (stub_h_exists, stub_c_exists, maybe_bcos, final_iface )
348            <- if toInterp
349 #ifdef GHCI
350                 then do 
351                     -----------------  Generate byte code ------------------
352                     (bcos,itbl_env) <- byteCodeGen dflags binds 
353                                         local_tycons local_classes
354
355                     -- Fill in the code-gen info
356                     writeIORef cg_info_ref (Just emptyNameEnv)
357
358                     ------------------ BUILD THE NEW ModIface ------------
359                     final_iface <- _scc_ "MkFinalIface" 
360                           mkFinalIface ghci_mode dflags location 
361                                    maybe_checked_iface new_iface tidy_details
362
363                     return ( False, False, Just (bcos,itbl_env), final_iface )
364 #else
365                 then error "GHC not compiled with interpreter"
366 #endif
367
368                 else do
369                     -----------------  Convert to STG ------------------
370                     (stg_binds, cost_centre_info, stg_back_end_info) 
371                               <- _scc_ "CoreToStg"
372                                  myCoreToStg dflags this_mod binds
373                     
374                     -- Fill in the code-gen info for the earlier tidyCorePgm
375                     writeIORef cg_info_ref (Just stg_back_end_info)
376
377                     ------------------ BUILD THE NEW ModIface ------------
378                     final_iface <- _scc_ "MkFinalIface" 
379                           mkFinalIface ghci_mode dflags location 
380                                    maybe_checked_iface new_iface tidy_details
381                     if toNothing 
382                       then do
383                           return (False, False, Nothing, final_iface)
384                       else do
385                           ------------------  Code generation ------------------
386                           abstractC <- _scc_ "CodeGen"
387                                        codeGen dflags this_mod imported_modules
388                                                cost_centre_info fe_binders
389                                                local_tycons stg_binds
390                           
391                           ------------------  Code output -----------------------
392                           (stub_h_exists, stub_c_exists)
393                              <- codeOutput dflags this_mod [] --local_tycons
394                                    binds stg_binds
395                                    c_code h_code abstractC
396                               
397                           return (stub_h_exists, stub_c_exists, Nothing, final_iface)
398
399           -- and the answer is ...
400         ; return (HscRecomp pcs_final
401                             final_details
402                             final_iface
403                             stub_h_exists stub_c_exists
404                             maybe_bcos)
405           }}}}}}}
406
407 myParseModule dflags src_filename
408  = do --------------------------  Parser  ----------------
409       showPass dflags "Parser"
410       _scc_  "Parser" do
411
412       buf <- hGetStringBuffer True{-expand tabs-} src_filename
413
414       let glaexts | dopt Opt_GlasgowExts dflags = 1#
415                   | otherwise                   = 0#
416
417       case parseModule buf PState{ bol = 0#, atbol = 1#,
418                                    context = [], glasgow_exts = glaexts,
419                                    loc = mkSrcLoc (_PK_ src_filename) 1 } of {
420
421         PFailed err -> do { hPutStrLn stderr (showSDoc err);
422                             freeStringBuffer buf;
423                             return Nothing };
424
425         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
426
427       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
428       
429       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
430                            (ppSourceStats False rdr_module) ;
431       
432       return (Just rdr_module)
433         -- ToDo: free the string buffer later.
434       }}
435
436
437 myCoreToStg dflags this_mod tidy_binds
438  = do 
439       () <- coreBindsSize tidy_binds `seq` return ()
440       -- TEMP: the above call zaps some space usage allocated by the
441       -- simplifier, which for reasons I don't understand, persists
442       -- thoroughout code generation -- JRS
443       --
444       -- This is still necessary. -- SDM (10 Dec 2001)
445
446       stg_binds <- _scc_ "Core2Stg" 
447              coreToStg dflags tidy_binds
448
449       (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg" 
450              stg2stg dflags this_mod stg_binds
451
452       let env_rhs :: CgInfoEnv
453           env_rhs = mkNameEnv [ caf_info `seq` (idName bndr, CgInfo caf_info)
454                               | (bind,_) <- stg_binds2, 
455                                 let caf_info 
456                                      | stgBindHasCafRefs bind = MayHaveCafRefs
457                                      | otherwise              = NoCafRefs,
458                                 bndr <- stgBinders bind ]
459
460       return (stg_binds2, cost_centre_info, env_rhs)
461 \end{code}
462
463
464 %************************************************************************
465 %*                                                                      *
466 \subsection{Compiling a do-statement}
467 %*                                                                      *
468 %************************************************************************
469
470 \begin{code}
471 #ifdef GHCI
472 hscStmt
473   :: DynFlags
474   -> HomeSymbolTable    
475   -> HomeIfaceTable
476   -> PersistentCompilerState    -- IN: persistent compiler state
477   -> InteractiveContext         -- Context for compiling
478   -> String                     -- The statement
479   -> Bool                       -- just treat it as an expression
480   -> IO ( PersistentCompilerState, 
481           Maybe ( [Id], 
482                   Type, 
483                   UnlinkedBCOExpr) )
484 \end{code}
485
486 When the UnlinkedBCOExpr is linked you get an HValue of type
487         IO [HValue]
488 When you run it you get a list of HValues that should be 
489 the same length as the list of names; add them to the ClosureEnv.
490
491 A naked expression returns a singleton Name [it].
492
493         What you type                   The IO [HValue] that hscStmt returns
494         -------------                   ------------------------------------
495         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
496                                         bindings: [x,y,...]
497
498         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
499                                         bindings: [x,y,...]
500
501         expr (of IO type)       ==>     expr >>= \ v -> return [v]
502           [NB: result not printed]      bindings: [it]
503           
504
505         expr (of non-IO type, 
506           result showable)      ==>     let v = expr in print v >> return [v]
507                                         bindings: [it]
508
509         expr (of non-IO type, 
510           result not showable)  ==>     error
511
512 \begin{code}
513 hscStmt dflags hst hit pcs0 icontext stmt just_expr
514    =  do { maybe_stmt <- hscParseStmt dflags stmt
515         ; case maybe_stmt of
516              Nothing -> return (pcs0, Nothing)
517              Just parsed_stmt -> do {
518
519            let { notExprStmt (ExprStmt _ _ _) = False;
520                  notExprStmt _                = True 
521                };
522
523            if (just_expr && notExprStmt parsed_stmt)
524                 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
525                         return (pcs0, Nothing)
526                 else do {
527
528                 -- Rename it
529           (pcs1, print_unqual, maybe_renamed_stmt)
530                  <- renameStmt dflags hit hst pcs0 icontext parsed_stmt
531
532         ; case maybe_renamed_stmt of
533                 Nothing -> return (pcs0, Nothing)
534                 Just (bound_names, rn_stmt) -> do {
535
536                 -- Typecheck it
537           maybe_tc_return <- 
538             if just_expr 
539                 then case rn_stmt of { (ExprStmt e _ _, decls) -> 
540                      typecheckExpr dflags pcs1 hst (ic_type_env icontext)
541                            print_unqual iNTERACTIVE (e,decls) }
542                 else typecheckStmt dflags pcs1 hst (ic_type_env icontext)
543                            print_unqual iNTERACTIVE bound_names rn_stmt
544
545         ; case maybe_tc_return of
546                 Nothing -> return (pcs0, Nothing)
547                 Just (pcs2, tc_expr, bound_ids, ty) ->  do {
548
549                 -- Desugar it
550           ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
551         
552                 -- Simplify it
553         ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
554
555                 -- Tidy it (temporary, until coreSat does cloning)
556         ; tidy_expr <- tidyCoreExpr simpl_expr
557
558                 -- Prepare for codegen
559         ; prepd_expr <- corePrepExpr dflags tidy_expr
560
561                 -- Convert to BCOs
562         ; bcos <- coreExprToBCOs dflags prepd_expr
563
564         ; let
565                 -- Make all the bound ids "global" ids, now that
566                 -- they're notionally top-level bindings.  This is
567                 -- important: otherwise when we come to compile an expression
568                 -- using these ids later, the byte code generator will consider
569                 -- the occurrences to be free rather than global.
570              global_bound_ids = map globaliseId bound_ids;
571              globaliseId id   = setGlobalIdDetails id VanillaGlobal
572
573         ; return (pcs2, Just (global_bound_ids, ty, bcos))
574
575      }}}}}
576
577 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
578 hscParseStmt dflags str
579  = do --------------------------  Parser  ----------------
580       showPass dflags "Parser"
581       _scc_ "Parser"  do
582
583       buf <- stringToStringBuffer str
584
585       let glaexts | dopt Opt_GlasgowExts dflags = 1#
586                   | otherwise                   = 0#
587
588       case parseStmt buf PState{ bol = 0#, atbol = 1#,
589                                  context = [], glasgow_exts = glaexts,
590                                  loc = mkSrcLoc SLIT("<interactive>") 1 } of {
591
592         PFailed err -> do { hPutStrLn stderr (showSDoc err);
593 --      Not yet implemented in <4.11    freeStringBuffer buf;
594                             return Nothing };
595
596         -- no stmt: the line consisted of just space or comments
597         POk _ Nothing -> return Nothing;
598
599         POk _ (Just rdr_stmt) -> do {
600
601       --ToDo: can't free the string buffer until we've finished this
602       -- compilation sweep and all the identifiers have gone away.
603       --freeStringBuffer buf;
604       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
605       return (Just rdr_stmt)
606       }}
607 #endif
608 \end{code}
609
610 %************************************************************************
611 %*                                                                      *
612 \subsection{Getting information about an identifer}
613 %*                                                                      *
614 %************************************************************************
615
616 \begin{code}
617 #ifdef GHCI
618 hscThing -- like hscStmt, but deals with a single identifier
619   :: DynFlags
620   -> HomeSymbolTable
621   -> HomeIfaceTable
622   -> PersistentCompilerState    -- IN: persistent compiler state
623   -> InteractiveContext         -- Context for compiling
624   -> String                     -- The identifier
625   -> IO ( PersistentCompilerState,
626           [TyThing] )
627
628 hscThing dflags hst hit pcs0 ic str
629    = do maybe_rdr_name <- myParseIdentifier dflags str
630         case maybe_rdr_name of {
631           Nothing -> return (pcs0, []);
632           Just rdr_name -> do
633
634         -- if the identifier is a constructor (begins with an
635         -- upper-case letter), then we need to consider both
636         -- constructor and type class identifiers.
637         let rdr_names
638                 | occNameSpace occ == dataName = [ rdr_name, tccls_name ]
639                 | otherwise                    = [ rdr_name ]
640               where
641                 occ        = rdrNameOcc rdr_name
642                 tccls_occ  = setOccNameSpace occ tcClsName
643                 tccls_name = setRdrNameOcc rdr_name tccls_occ
644
645         (pcs, unqual, maybe_rn_result) <- 
646            renameRdrName dflags hit hst pcs0 ic rdr_names
647
648         case maybe_rn_result of {
649              Nothing -> return (pcs, []);
650              Just (names, decls) -> do {
651
652         maybe_pcs <- typecheckExtraDecls dflags pcs hst unqual
653                         iNTERACTIVE decls;
654
655         case maybe_pcs of {
656              Nothing -> return (pcs, []);
657              Just pcs ->
658                 let do_lookup n
659                         | isLocalName n = lookupNameEnv (ic_type_env ic) n
660                         | otherwise     = lookupType hst (pcs_PTE pcs) n
661                 
662                     maybe_ty_things = map do_lookup names
663                 in
664                 return (pcs, catMaybes maybe_ty_things) }
665         }}}
666
667 myParseIdentifier dflags str
668   = do buf <- stringToStringBuffer str
669  
670        let glaexts | dopt Opt_GlasgowExts dflags = 1#
671                    | otherwise                   = 0#
672
673        case parseIdentifier buf 
674                 PState{ bol = 0#, atbol = 1#,
675                         context = [], glasgow_exts = glaexts,
676                         loc = mkSrcLoc SLIT("<interactive>") 1 } of
677
678           PFailed err -> do { hPutStrLn stderr (showSDoc err);
679                               freeStringBuffer buf;
680                               return Nothing }
681
682           POk _ rdr_name -> do { --should, but can't: freeStringBuffer buf;
683                                  return (Just rdr_name) }
684 #endif
685 \end{code}
686
687 %************************************************************************
688 %*                                                                      *
689 \subsection{Find all the things defined in a module}
690 %*                                                                      *
691 %************************************************************************
692
693 \begin{code}
694 #ifdef GHCI
695 hscModuleContents
696   :: DynFlags
697   -> HomeSymbolTable
698   -> HomeIfaceTable
699   -> PersistentCompilerState    -- IN: persistent compiler state
700   -> Module                     -- module to inspect
701   -> Bool                       -- grab just the exports, or the whole toplev
702   -> IO (PersistentCompilerState, Maybe [TyThing])
703
704 hscModuleContents dflags hst hit pcs0 mod exports_only = do {
705
706   -- slurp the interface if necessary
707   (pcs1, print_unqual, maybe_rn_stuff) 
708         <- slurpIface dflags hit hst pcs0 mod;
709
710   case maybe_rn_stuff of {
711         Nothing -> return (pcs0, Nothing);
712         Just (names, rn_decls) -> do {
713
714   -- Typecheck the declarations
715   maybe_pcs <-
716      typecheckExtraDecls dflags pcs1 hst print_unqual iNTERACTIVE rn_decls;
717
718   case maybe_pcs of {
719         Nothing   -> return (pcs1, Nothing);
720         Just pcs2 -> 
721
722   let { all_names 
723            | exports_only = names
724            | otherwise =
725              let { iface = fromJust (lookupModuleEnv hit mod);
726                    env   = fromJust (mi_globals iface);
727                    range = rdrEnvElts env;
728              } in
729              -- grab all the things from the global env that are locally def'd
730              nub [ n | elts <- range, GRE n LocalDef _ <- elts ];
731
732         pte = pcs_PTE pcs2;
733
734         ty_things = map (fromJust . lookupType hst pte) all_names;
735
736       } in
737
738   return (pcs2, Just ty_things)
739   }}}}
740 #endif
741 \end{code}
742
743 %************************************************************************
744 %*                                                                      *
745 \subsection{Initial persistent state}
746 %*                                                                      *
747 %************************************************************************
748
749 \begin{code}
750 initPersistentCompilerState :: IO PersistentCompilerState
751 initPersistentCompilerState 
752   = do prs <- initPersistentRenamerState
753        return (
754         PCS { pcs_PIT   = emptyIfaceTable,
755               pcs_PTE   = wiredInThingEnv,
756               pcs_insts = emptyInstEnv,
757               pcs_rules = emptyRuleBase,
758               pcs_PRS   = prs
759             }
760         )
761
762 initPersistentRenamerState :: IO PersistentRenamerState
763   = do us <- mkSplitUniqSupply 'r'
764        return (
765         PRS { prsOrig  = NameSupply { nsUniqs = us,
766                                       nsNames = initOrigNames,
767                                       nsIPs   = emptyFM },
768               prsDecls   = (emptyNameEnv, 0),
769               prsInsts   = (emptyBag, 0),
770               prsRules   = foldr add_rule (emptyBag, 0) builtinRules,
771               prsImpMods = emptyFM
772             }
773         )
774   where
775     add_rule (name,rule) (rules, n_rules)
776          = (gated_decl `consBag` rules, n_rules+1)
777         where
778            gated_decl = (gate_fn, (mod, IfaceRuleOut rdr_name rule))
779            mod        = nameModule name
780            rdr_name   = mkRdrOrig (moduleName mod) (nameOccName name)
781            gate_fn vis_fn = vis_fn name -- Load the rule whenever name is visible
782
783 initOrigNames :: FiniteMap (ModuleName,OccName) Name
784 initOrigNames 
785    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
786      where
787         grab names = foldl add emptyFM names
788         add env name 
789            = addToFM env (moduleName (nameModule name), nameOccName name) name
790 \end{code}