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