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