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