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