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