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