[project @ 2002-03-20 11:24:42 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 TidyPgm          ( 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             ( isInternalName )
30 import NameEnv          ( lookupNameEnv )
31 import Module           ( lookupModuleEnv )
32 import RdrName          ( rdrEnvElts )
33 import PrelNames        ( iNTERACTIVE )
34 import StringBuffer     ( stringToStringBuffer )
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              ( ParseResult(..), ExtFlags(..), mkPState )
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, gHC_PRIM_Name )
55 import MkIface          ( mkFinalIface )
56 import TcModule
57 import InstEnv          ( emptyInstEnv )
58 import Desugar
59 import Flattening       ( flatten, flattenExpr )
60 import SimplCore
61 import CoreUtils        ( coreBindsSize )
62 import TidyPgm          ( tidyCorePgm )
63 import CorePrep         ( corePrepPgm )
64 import StgSyn
65 import CoreToStg        ( coreToStg )
66 import SimplStg         ( stg2stg )
67 import CodeGen          ( codeGen )
68 import CodeOutput       ( codeOutput, outputForeignStubs )
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 )
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             -------------------
249             -- FLATTENING
250             -------------------
251         ; flat_details
252              <- _scc_ "Flattening"
253                 flatten dflags pcs_tc hst ds_details
254
255         ; pcs_middle
256             <- _scc_ "pcs_middle"
257                 if ghci_mode == OneShot 
258                   then do init_pcs <- initPersistentCompilerState
259                           init_prs <- initPersistentRenamerState
260                           let 
261                               rules   = pcs_rules pcs_tc        
262                               orig_tc = prsOrig (pcs_PRS pcs_tc)
263                               new_prs = init_prs{ prsOrig=orig_tc }
264
265                           orig_tc `seq` rules `seq` new_prs `seq`
266                             return init_pcs{ pcs_PRS = new_prs,
267                                              pcs_rules = rules }
268                   else return pcs_tc
269
270         -- alive at this point:  
271         --      pcs_middle
272         --      foreign_stuff
273         --      ds_details
274         --      new_iface               
275
276             -------------------
277             -- SIMPLIFY
278             -------------------
279         ; simpl_details
280              <- _scc_     "Core2Core"
281                 core2core dflags pcs_middle hst dont_discard flat_details
282
283             -------------------
284             -- TIDY
285             -------------------
286         ; cg_info_ref <- newIORef Nothing ;
287         ; let cg_info :: CgInfoEnv
288               cg_info = unsafePerformIO $ do {
289                            maybe_cg_env <- readIORef cg_info_ref ;
290                            case maybe_cg_env of
291                              Just env -> return env
292                              Nothing  -> do { printError "Urk! Looked at CgInfo too early!";
293                                               return emptyNameEnv } }
294                 -- cg_info_ref will be filled in just after restOfCodeGeneration
295                 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
296
297         ; (pcs_simpl, tidy_details) 
298              <- _scc_ "CoreTidy"
299                 tidyCorePgm dflags this_mod pcs_middle cg_info simpl_details
300       
301         ; pcs_final <- if ghci_mode == OneShot then initPersistentCompilerState
302                                                else return pcs_simpl
303
304         -- alive at this point:  
305         --      tidy_details
306         --      new_iface               
307
308         ; emitExternalCore dflags new_iface tidy_details 
309
310         ; let final_details = tidy_details {md_binds = []} 
311         ; final_details `seq` return ()
312
313             -------------------
314             -- PREPARE FOR CODE GENERATION
315             -------------------
316               -- Do saturation and convert to A-normal form
317         ; prepd_details <- _scc_ "CorePrep" 
318                            corePrepPgm dflags tidy_details
319
320             -------------------
321             -- CONVERT TO STG and COMPLETE CODE GENERATION
322             -------------------
323         ; let
324             ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
325
326             local_tycons     = typeEnvTyCons  env_tc
327             local_classes    = typeEnvClasses env_tc
328
329             imported_module_names = 
330                 filter (/= gHC_PRIM_Name) $
331                 map ideclName (hsModuleImports rdr_module)
332                 -- eek! doesn't this keep rdr_module live until code generation?
333                 -- SDM 3/2002
334
335             mod_name_to_Module nm
336                  = do m <- findModule nm ; return (fst (fromJust m))
337
338             (h_code, c_code, headers, fe_binders) = foreign_stuff
339
340             -- turn the list of headers requested in foreign import
341             -- declarations into a string suitable for emission into generated
342             -- C code...
343             --
344             foreign_headers =   
345                 unlines 
346               . map (\fname -> "#include \"" ++ _UNPK_ fname ++ "\"")
347               . reverse 
348               $ headers
349
350           -- ...and add the string to the headers requested via command line
351           -- options 
352           --
353         ; fhdrs <- readIORef v_HCHeader
354         ; writeIORef v_HCHeader (fhdrs ++ foreign_headers)
355
356         ; imported_modules <- mapM mod_name_to_Module imported_module_names
357
358         ; (stub_h_exists, stub_c_exists, maybe_bcos, final_iface )
359            <- if toInterp
360 #ifdef GHCI
361                 then do 
362                     -----------------  Generate byte code ------------------
363                     (bcos,itbl_env) <- byteCodeGen dflags binds 
364                                         local_tycons local_classes
365
366                     -- Fill in the code-gen info
367                     writeIORef cg_info_ref (Just emptyNameEnv)
368
369                     ------------------ BUILD THE NEW ModIface ------------
370                     final_iface <- _scc_ "MkFinalIface" 
371                           mkFinalIface ghci_mode dflags location 
372                                    maybe_checked_iface new_iface tidy_details
373
374                     ------------------ Create f-x-dynamic C-side stuff ---
375                     (istub_h_exists, istub_c_exists) 
376                        <- outputForeignStubs dflags c_code h_code
377
378                     return ( istub_h_exists, istub_c_exists, 
379                              Just (bcos,itbl_env), final_iface )
380 #else
381                 then error "GHC not compiled with interpreter"
382 #endif
383
384                 else do
385                     -----------------  Convert to STG ------------------
386                     (stg_binds, cost_centre_info, stg_back_end_info) 
387                               <- _scc_ "CoreToStg"
388                                  myCoreToStg dflags this_mod binds
389                     
390                     -- Fill in the code-gen info for the earlier tidyCorePgm
391                     writeIORef cg_info_ref (Just stg_back_end_info)
392
393                     ------------------ BUILD THE NEW ModIface ------------
394                     final_iface <- _scc_ "MkFinalIface" 
395                           mkFinalIface ghci_mode dflags location 
396                                    maybe_checked_iface new_iface tidy_details
397                     if toNothing 
398                       then do
399                           return (False, False, Nothing, final_iface)
400                       else do
401                           ------------------  Code generation ------------------
402                           abstractC <- _scc_ "CodeGen"
403                                        codeGen dflags this_mod imported_modules
404                                                cost_centre_info fe_binders
405                                                local_tycons stg_binds
406                           
407                           ------------------  Code output -----------------------
408                           (stub_h_exists, stub_c_exists)
409                              <- codeOutput dflags this_mod [] --local_tycons
410                                    binds stg_binds
411                                    c_code h_code abstractC
412                               
413                           return (stub_h_exists, stub_c_exists, Nothing, final_iface)
414
415           -- and the answer is ...
416         ; return (HscRecomp pcs_final
417                             final_details
418                             final_iface
419                             stub_h_exists stub_c_exists
420                             maybe_bcos)
421           }}}}}}}
422
423 myParseModule dflags src_filename
424  = do --------------------------  Parser  ----------------
425       showPass dflags "Parser"
426       _scc_  "Parser" do
427
428       buf <- hGetStringBuffer src_filename
429
430       let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
431                            parrEF        = dopt Opt_PArr        dflags}
432           loc  = mkSrcLoc (_PK_ src_filename) 1
433
434       case parseModule buf (mkPState loc exts) of {
435
436         PFailed err -> do { hPutStrLn stderr (showSDoc err);
437                             freeStringBuffer buf;
438                             return Nothing };
439
440         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
441
442       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
443       
444       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
445                            (ppSourceStats False rdr_module) ;
446       
447       return (Just rdr_module)
448         -- ToDo: free the string buffer later.
449       }}
450
451
452 myCoreToStg dflags this_mod tidy_binds
453  = do 
454       () <- coreBindsSize tidy_binds `seq` return ()
455       -- TEMP: the above call zaps some space usage allocated by the
456       -- simplifier, which for reasons I don't understand, persists
457       -- thoroughout code generation -- JRS
458       --
459       -- This is still necessary. -- SDM (10 Dec 2001)
460
461       stg_binds <- _scc_ "Core2Stg" 
462              coreToStg dflags tidy_binds
463
464       (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg" 
465              stg2stg dflags this_mod stg_binds
466
467       let env_rhs :: CgInfoEnv
468           env_rhs = mkNameEnv [ caf_info `seq` (idName bndr, CgInfo caf_info)
469                               | (bind,_) <- stg_binds2, 
470                                 let caf_info 
471                                      | stgBindHasCafRefs bind = MayHaveCafRefs
472                                      | otherwise              = NoCafRefs,
473                                 bndr <- stgBinders bind ]
474
475       return (stg_binds2, cost_centre_info, env_rhs)
476 \end{code}
477
478
479 %************************************************************************
480 %*                                                                      *
481 \subsection{Compiling a do-statement}
482 %*                                                                      *
483 %************************************************************************
484
485 \begin{code}
486 #ifdef GHCI
487 hscStmt
488   :: DynFlags
489   -> HomeSymbolTable    
490   -> HomeIfaceTable
491   -> PersistentCompilerState    -- IN: persistent compiler state
492   -> InteractiveContext         -- Context for compiling
493   -> String                     -- The statement
494   -> Bool                       -- just treat it as an expression
495   -> IO ( PersistentCompilerState, 
496           Maybe ( [Id], 
497                   Type, 
498                   UnlinkedBCOExpr) )
499 \end{code}
500
501 When the UnlinkedBCOExpr is linked you get an HValue of type
502         IO [HValue]
503 When you run it you get a list of HValues that should be 
504 the same length as the list of names; add them to the ClosureEnv.
505
506 A naked expression returns a singleton Name [it].
507
508         What you type                   The IO [HValue] that hscStmt returns
509         -------------                   ------------------------------------
510         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
511                                         bindings: [x,y,...]
512
513         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
514                                         bindings: [x,y,...]
515
516         expr (of IO type)       ==>     expr >>= \ v -> return [v]
517           [NB: result not printed]      bindings: [it]
518           
519
520         expr (of non-IO type, 
521           result showable)      ==>     let v = expr in print v >> return [v]
522                                         bindings: [it]
523
524         expr (of non-IO type, 
525           result not showable)  ==>     error
526
527 \begin{code}
528 hscStmt dflags hst hit pcs0 icontext stmt just_expr
529    =  do { maybe_stmt <- hscParseStmt dflags stmt
530         ; case maybe_stmt of
531              Nothing -> return (pcs0, Nothing)
532              Just parsed_stmt -> do {
533
534            let { notExprStmt (ExprStmt _ _ _) = False;
535                  notExprStmt _                = True 
536                };
537
538            if (just_expr && notExprStmt parsed_stmt)
539                 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
540                         return (pcs0, Nothing)
541                 else do {
542
543                 -- Rename it
544           (pcs1, print_unqual, maybe_renamed_stmt)
545                  <- renameStmt dflags hit hst pcs0 icontext parsed_stmt
546
547         ; case maybe_renamed_stmt of
548                 Nothing -> return (pcs0, Nothing)
549                 Just (bound_names, rn_stmt) -> do {
550
551                 -- Typecheck it
552           maybe_tc_return <- 
553             if just_expr 
554                 then case rn_stmt of { (ExprStmt e _ _, decls) -> 
555                      typecheckExpr dflags pcs1 hst (ic_type_env icontext)
556                            print_unqual iNTERACTIVE (e,decls) }
557                 else typecheckStmt dflags pcs1 hst (ic_type_env icontext)
558                            print_unqual iNTERACTIVE bound_names rn_stmt
559
560         ; case maybe_tc_return of
561                 Nothing -> return (pcs0, Nothing)
562                 Just (pcs2, tc_expr, bound_ids, ty) ->  do {
563
564                 -- Desugar it
565           ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
566         
567                 -- Flatten it
568         ; flat_expr <- flattenExpr dflags pcs2 hst ds_expr
569
570                 -- Simplify it
571         ; simpl_expr <- simplifyExpr dflags pcs2 hst flat_expr
572
573                 -- Tidy it (temporary, until coreSat does cloning)
574         ; tidy_expr <- tidyCoreExpr simpl_expr
575
576                 -- Prepare for codegen
577         ; prepd_expr <- corePrepExpr dflags tidy_expr
578
579                 -- Convert to BCOs
580         ; bcos <- coreExprToBCOs dflags prepd_expr
581
582         ; let
583                 -- Make all the bound ids "global" ids, now that
584                 -- they're notionally top-level bindings.  This is
585                 -- important: otherwise when we come to compile an expression
586                 -- using these ids later, the byte code generator will consider
587                 -- the occurrences to be free rather than global.
588              global_bound_ids = map globaliseId bound_ids;
589              globaliseId id   = setGlobalIdDetails id VanillaGlobal
590
591         ; return (pcs2, Just (global_bound_ids, ty, bcos))
592
593      }}}}}
594
595 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
596 hscParseStmt dflags str
597  = do --------------------------  Parser  ----------------
598       showPass dflags "Parser"
599       _scc_ "Parser"  do
600
601       buf <- stringToStringBuffer str
602
603       let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
604                            parrEF        = dopt Opt_PArr        dflags}
605           loc  = mkSrcLoc SLIT("<interactive>") 1
606
607       case parseStmt buf (mkPState loc exts) of {
608
609         PFailed err -> do { hPutStrLn stderr (showSDoc err);
610 --      Not yet implemented in <4.11    freeStringBuffer buf;
611                             return Nothing };
612
613         -- no stmt: the line consisted of just space or comments
614         POk _ Nothing -> return Nothing;
615
616         POk _ (Just rdr_stmt) -> do {
617
618       --ToDo: can't free the string buffer until we've finished this
619       -- compilation sweep and all the identifiers have gone away.
620       --freeStringBuffer buf;
621       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
622       return (Just rdr_stmt)
623       }}
624 #endif
625 \end{code}
626
627 %************************************************************************
628 %*                                                                      *
629 \subsection{Getting information about an identifer}
630 %*                                                                      *
631 %************************************************************************
632
633 \begin{code}
634 #ifdef GHCI
635 hscThing -- like hscStmt, but deals with a single identifier
636   :: DynFlags
637   -> HomeSymbolTable
638   -> HomeIfaceTable
639   -> PersistentCompilerState    -- IN: persistent compiler state
640   -> InteractiveContext         -- Context for compiling
641   -> String                     -- The identifier
642   -> IO ( PersistentCompilerState,
643           [TyThing] )
644
645 hscThing dflags hst hit pcs0 ic str
646    = do maybe_rdr_name <- myParseIdentifier dflags str
647         case maybe_rdr_name of {
648           Nothing -> return (pcs0, []);
649           Just rdr_name -> do
650
651         -- if the identifier is a constructor (begins with an
652         -- upper-case letter), then we need to consider both
653         -- constructor and type class identifiers.
654         let rdr_names
655                 | occNameSpace occ == dataName = [ rdr_name, tccls_name ]
656                 | otherwise                    = [ rdr_name ]
657               where
658                 occ        = rdrNameOcc rdr_name
659                 tccls_occ  = setOccNameSpace occ tcClsName
660                 tccls_name = setRdrNameOcc rdr_name tccls_occ
661
662         (pcs, unqual, maybe_rn_result) <- 
663            renameRdrName dflags hit hst pcs0 ic rdr_names
664
665         case maybe_rn_result of {
666              Nothing -> return (pcs, []);
667              Just (names, decls) -> do {
668
669         maybe_pcs <- typecheckExtraDecls dflags pcs hst unqual
670                         iNTERACTIVE decls;
671
672         case maybe_pcs of {
673              Nothing -> return (pcs, []);
674              Just pcs ->
675                 let do_lookup n
676                         | isInternalName n = lookupNameEnv (ic_type_env ic) n
677                         | otherwise     = lookupType hst (pcs_PTE pcs) n
678                 
679                     maybe_ty_things = map do_lookup names
680                 in
681                 return (pcs, catMaybes maybe_ty_things) }
682         }}}
683
684 myParseIdentifier dflags str
685   = do buf <- stringToStringBuffer str
686  
687        let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
688                             parrEF        = dopt Opt_PArr        dflags}
689            loc  = mkSrcLoc SLIT("<interactive>") 1
690
691        case parseIdentifier buf (mkPState loc exts) of
692
693           PFailed err -> do { hPutStrLn stderr (showSDoc err);
694                               freeStringBuffer buf;
695                               return Nothing }
696
697           POk _ rdr_name -> do { --should, but can't: freeStringBuffer buf;
698                                  return (Just rdr_name) }
699 #endif
700 \end{code}
701
702 %************************************************************************
703 %*                                                                      *
704 \subsection{Find all the things defined in a module}
705 %*                                                                      *
706 %************************************************************************
707
708 \begin{code}
709 #ifdef GHCI
710 hscModuleContents
711   :: DynFlags
712   -> HomeSymbolTable
713   -> HomeIfaceTable
714   -> PersistentCompilerState    -- IN: persistent compiler state
715   -> Module                     -- module to inspect
716   -> Bool                       -- grab just the exports, or the whole toplev
717   -> IO (PersistentCompilerState, Maybe [TyThing])
718
719 hscModuleContents dflags hst hit pcs0 mod exports_only = do {
720
721   -- slurp the interface if necessary
722   (pcs1, print_unqual, maybe_rn_stuff) 
723         <- slurpIface dflags hit hst pcs0 mod;
724
725   case maybe_rn_stuff of {
726         Nothing -> return (pcs0, Nothing);
727         Just (names, rn_decls) -> do {
728
729   -- Typecheck the declarations
730   maybe_pcs <-
731      typecheckExtraDecls dflags pcs1 hst print_unqual iNTERACTIVE rn_decls;
732
733   case maybe_pcs of {
734         Nothing   -> return (pcs1, Nothing);
735         Just pcs2 -> 
736
737   let { all_names 
738            | exports_only = names
739            | otherwise =
740              let { iface = fromJust (lookupModuleEnv hit mod);
741                    env   = fromJust (mi_globals iface);
742                    range = rdrEnvElts env;
743              } in
744              -- grab all the things from the global env that are locally def'd
745              nub [ n | elts <- range, GRE n LocalDef _ <- elts ];
746
747         pte = pcs_PTE pcs2;
748
749         ty_things = map (fromJust . lookupType hst pte) all_names;
750
751       } in
752
753   return (pcs2, Just ty_things)
754   }}}}
755 #endif
756 \end{code}
757
758 %************************************************************************
759 %*                                                                      *
760 \subsection{Initial persistent state}
761 %*                                                                      *
762 %************************************************************************
763
764 \begin{code}
765 initPersistentCompilerState :: IO PersistentCompilerState
766 initPersistentCompilerState 
767   = do prs <- initPersistentRenamerState
768        return (
769         PCS { pcs_PIT   = emptyIfaceTable,
770               pcs_PTE   = wiredInThingEnv,
771               pcs_insts = emptyInstEnv,
772               pcs_rules = emptyRuleBase,
773               pcs_PRS   = prs
774             }
775         )
776
777 initPersistentRenamerState :: IO PersistentRenamerState
778   = do us <- mkSplitUniqSupply 'r'
779        return (
780         PRS { prsOrig  = NameSupply { nsUniqs = us,
781                                       nsNames = initOrigNames,
782                                       nsIPs   = emptyFM },
783               prsDecls   = (emptyNameEnv, 0),
784               prsInsts   = (emptyBag, 0),
785               prsRules   = foldr add_rule (emptyBag, 0) builtinRules,
786               prsImpMods = emptyFM
787             }
788         )
789   where
790     add_rule (name,rule) (rules, n_rules)
791          = (gated_decl `consBag` rules, n_rules+1)
792         where
793            gated_decl = (gate_fn, (mod, IfaceRuleOut rdr_name rule))
794            mod        = nameModule name
795            rdr_name   = mkRdrOrig (moduleName mod) (nameOccName name)
796            gate_fn vis_fn = vis_fn name -- Load the rule whenever name is visible
797
798 initOrigNames :: FiniteMap (ModuleName,OccName) Name
799 initOrigNames 
800    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
801      where
802         grab names = foldl add emptyFM names
803         add env name 
804            = addToFM env (moduleName (nameModule name), nameOccName name) name
805 \end{code}