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