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