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