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