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