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