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