[project @ 2002-05-03 11:23:41 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 (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 -- Should we remove bits of flat_details at this point?
265 --         ; flat_details <- case flat_details of
266 --                             ModDetails { md_binds = binds } ->
267 --                                 return ModDetails { md_binds = binds,
268 --                                                     md_rules = [],
269 --                                                     md_types = emptyTypeEnv,
270 --                                                     md_insts = [] }
271
272         -- alive at this point:  
273         --      pcs_middle
274         --      foreign_stuff
275         --      flat_details
276         --      imported_modules (seq'd)
277         --      new_iface
278
279             -------------------
280             -- SIMPLIFY
281             -------------------
282         ; simpl_details
283              <- _scc_     "Core2Core"
284                 core2core dflags pcs_middle hst dont_discard flat_details
285
286             -------------------
287             -- TIDY
288             -------------------
289         ; cg_info_ref <- newIORef Nothing ;
290         ; let cg_info :: CgInfoEnv
291               cg_info = unsafePerformIO $ do {
292                            maybe_cg_env <- readIORef cg_info_ref ;
293                            case maybe_cg_env of
294                              Just env -> return env
295                              Nothing  -> do { printError "Urk! Looked at CgInfo too early!";
296                                               return emptyNameEnv } }
297                 -- cg_info_ref will be filled in just after restOfCodeGeneration
298                 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
299
300         ; (pcs_simpl, tidy_details) 
301              <- _scc_ "CoreTidy"
302                 tidyCorePgm dflags this_mod pcs_middle cg_info simpl_details
303       
304         ; pcs_final <- if ghci_mode == OneShot then initPersistentCompilerState
305                                                else return pcs_simpl
306
307         -- alive at this point:  
308         --      tidy_details
309         --      new_iface               
310
311         ; emitExternalCore dflags new_iface tidy_details 
312
313         ; let final_details = tidy_details {md_binds = []} 
314         ; final_details `seq` return ()
315
316             -------------------
317             -- PREPARE FOR CODE GENERATION
318             -------------------
319               -- Do saturation and convert to A-normal form
320         ; prepd_details <- _scc_ "CorePrep" 
321                            corePrepPgm dflags tidy_details
322
323             -------------------
324             -- CONVERT TO STG and COMPLETE CODE GENERATION
325             -------------------
326         ; let
327             ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
328
329             local_tycons     = typeEnvTyCons  env_tc
330             local_classes    = typeEnvClasses env_tc
331
332             (h_code, c_code, headers, fe_binders) = foreign_stuff
333
334             -- turn the list of headers requested in foreign import
335             -- declarations into a string suitable for emission into generated
336             -- C code...
337             --
338             foreign_headers =   
339                 unlines 
340               . map (\fname -> "#include \"" ++ unpackFS fname ++ "\"")
341               . reverse 
342               $ headers
343
344           -- ...and add the string to the headers requested via command line
345           -- options 
346           --
347         ; fhdrs <- readIORef v_HCHeader
348         ; writeIORef v_HCHeader (fhdrs ++ foreign_headers)
349
350         ; (stub_h_exists, stub_c_exists, maybe_bcos, final_iface )
351            <- if toInterp
352 #ifdef GHCI
353                 then do 
354                     -----------------  Generate byte code ------------------
355                     (bcos,itbl_env) <- byteCodeGen dflags binds 
356                                         local_tycons local_classes
357
358                     -- Fill in the code-gen info
359                     writeIORef cg_info_ref (Just emptyNameEnv)
360
361                     ------------------ BUILD THE NEW ModIface ------------
362                     final_iface <- _scc_ "MkFinalIface" 
363                           mkFinalIface ghci_mode dflags location 
364                                    maybe_checked_iface new_iface tidy_details
365
366                     ------------------ Create f-x-dynamic C-side stuff ---
367                     (istub_h_exists, istub_c_exists) 
368                        <- outputForeignStubs dflags c_code h_code
369
370                     return ( istub_h_exists, istub_c_exists, 
371                              Just (bcos,itbl_env), final_iface )
372 #else
373                 then error "GHC not compiled with interpreter"
374 #endif
375
376                 else do
377                     -----------------  Convert to STG ------------------
378                     (stg_binds, cost_centre_info, stg_back_end_info) 
379                               <- _scc_ "CoreToStg"
380                                  myCoreToStg dflags this_mod binds
381                     
382                     -- Fill in the code-gen info for the earlier tidyCorePgm
383                     writeIORef cg_info_ref (Just stg_back_end_info)
384
385                     ------------------ BUILD THE NEW ModIface ------------
386                     final_iface <- _scc_ "MkFinalIface" 
387                           mkFinalIface ghci_mode dflags location 
388                                    maybe_checked_iface new_iface tidy_details
389                     if toNothing 
390                       then do
391                           return (False, False, Nothing, final_iface)
392                       else do
393                           ------------------  Code generation ------------------
394                           abstractC <- _scc_ "CodeGen"
395                                        codeGen dflags this_mod imported_modules
396                                                cost_centre_info fe_binders
397                                                local_tycons stg_binds
398                           
399                           ------------------  Code output -----------------------
400                           (stub_h_exists, stub_c_exists)
401                              <- codeOutput dflags this_mod [] --local_tycons
402                                    binds stg_binds
403                                    c_code h_code abstractC
404                               
405                           return (stub_h_exists, stub_c_exists, Nothing, final_iface)
406
407           -- and the answer is ...
408         ; return (HscRecomp pcs_final
409                             final_details
410                             final_iface
411                             stub_h_exists stub_c_exists
412                             maybe_bcos)
413          }}
414
415 hscCoreFrontEnd ghci_mode dflags location hst hit pcs_ch = do {
416             -------------------
417             -- PARSE
418             -------------------
419         ; inp <- readFile (expectJust "hscCoreFrontEnd:hspp" (ml_hspp_file location))
420         ; case parseCore inp 1 of
421             FailP s        -> hPutStrLn stderr s >> return (Left (HscFail pcs_ch));
422             OkP rdr_module -> do {
423         ; let this_mod = mkHomeModule (hsModuleName rdr_module)
424     
425             -------------------
426             -- RENAME
427             -------------------
428         ; (pcs_rn, print_unqual, maybe_rn_result) 
429              <- renameExtCore dflags hit hst pcs_ch this_mod rdr_module
430         ; case maybe_rn_result of {
431              Nothing -> return (Left (HscFail pcs_ch));
432              Just (dont_discard, new_iface, rn_decls) -> do {
433
434             -------------------
435             -- TYPECHECK
436             -------------------
437         ; maybe_tc_result 
438             <- _scc_ "TypeCheck" 
439                typecheckCoreModule dflags pcs_rn hst new_iface rn_decls
440         ; case maybe_tc_result of {
441              Nothing -> return (Left (HscFail pcs_ch));
442              Just (pcs_tc, tc_result) -> do {
443     
444             -------------------
445             -- DESUGAR
446             -------------------
447         ; (ds_details, foreign_stuff) <- deSugarCore tc_result
448         ; return (Right (this_mod, rdr_module, dont_discard, new_iface,
449                          pcs_tc, ds_details, foreign_stuff))
450         }}}}}}
451          
452
453 hscFrontEnd ghci_mode dflags location hst hit pcs_ch = do {
454             -------------------
455             -- PARSE
456             -------------------
457         ; maybe_parsed <- myParseModule dflags 
458                              (expectJust "hscRecomp:hspp" (ml_hspp_file location))
459         ; case maybe_parsed of {
460              Nothing -> return (Left (HscFail pcs_ch));
461              Just rdr_module -> do {
462         ; let this_mod = mkHomeModule (hsModuleName rdr_module)
463     
464             -------------------
465             -- RENAME
466             -------------------
467         ; (pcs_rn, print_unqual, maybe_rn_result) 
468              <- _scc_ "Rename" 
469                  renameModule dflags ghci_mode hit hst pcs_ch this_mod rdr_module
470         ; case maybe_rn_result of {
471              Nothing -> return (Left (HscFail pcs_ch));
472              Just (dont_discard, new_iface, rn_result) -> do {
473
474             -------------------
475             -- TYPECHECK
476             -------------------
477         ; maybe_tc_result 
478             <- _scc_ "TypeCheck" 
479                typecheckModule dflags pcs_rn hst print_unqual rn_result
480         ; case maybe_tc_result of {
481              Nothing -> return (Left (HscFail pcs_ch));
482              Just (pcs_tc, tc_result) -> do {
483     
484             -------------------
485             -- DESUGAR
486             -------------------
487         ; (ds_details, foreign_stuff) 
488              <- _scc_ "DeSugar" 
489                 deSugar dflags pcs_tc hst this_mod print_unqual tc_result
490         ; return (Right (this_mod, rdr_module, dont_discard, new_iface,
491                          pcs_tc, ds_details, foreign_stuff))
492         }}}}}}}
493
494
495 myParseModule dflags src_filename
496  = do --------------------------  Parser  ----------------
497       showPass dflags "Parser"
498       _scc_  "Parser" do
499       buf <- hGetStringBuffer src_filename
500
501       let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
502                            parrEF        = dopt Opt_PArr        dflags}
503           loc  = mkSrcLoc (mkFastString src_filename) 1
504
505       case parseModule buf (mkPState loc exts) of {
506
507         PFailed err -> do { hPutStrLn stderr (showSDoc err);
508                             freeStringBuffer buf;
509                             return Nothing };
510
511         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
512
513       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
514       
515       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
516                            (ppSourceStats False rdr_module) ;
517       
518       return (Just rdr_module)
519         -- ToDo: free the string buffer later.
520       }}
521
522
523 myCoreToStg dflags this_mod tidy_binds
524  = do 
525       () <- coreBindsSize tidy_binds `seq` return ()
526       -- TEMP: the above call zaps some space usage allocated by the
527       -- simplifier, which for reasons I don't understand, persists
528       -- thoroughout code generation -- JRS
529       --
530       -- This is still necessary. -- SDM (10 Dec 2001)
531
532       stg_binds <- _scc_ "Core2Stg" 
533              coreToStg dflags tidy_binds
534
535       (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg" 
536              stg2stg dflags this_mod stg_binds
537
538       let env_rhs :: CgInfoEnv
539           env_rhs = mkNameEnv [ caf_info `seq` (idName bndr, CgInfo caf_info)
540                               | (bind,_) <- stg_binds2, 
541                                 let caf_info 
542                                      | stgBindHasCafRefs bind = MayHaveCafRefs
543                                      | otherwise              = NoCafRefs,
544                                 bndr <- stgBinders bind ]
545
546       return (stg_binds2, cost_centre_info, env_rhs)
547 \end{code}
548
549
550 %************************************************************************
551 %*                                                                      *
552 \subsection{Compiling a do-statement}
553 %*                                                                      *
554 %************************************************************************
555
556 \begin{code}
557 #ifdef GHCI
558 hscStmt
559   :: DynFlags
560   -> HomeSymbolTable    
561   -> HomeIfaceTable
562   -> PersistentCompilerState    -- IN: persistent compiler state
563   -> InteractiveContext         -- Context for compiling
564   -> String                     -- The statement
565   -> Bool                       -- just treat it as an expression
566   -> IO ( PersistentCompilerState, 
567           Maybe ( [Id], 
568                   Type, 
569                   UnlinkedBCOExpr) )
570 \end{code}
571
572 When the UnlinkedBCOExpr is linked you get an HValue of type
573         IO [HValue]
574 When you run it you get a list of HValues that should be 
575 the same length as the list of names; add them to the ClosureEnv.
576
577 A naked expression returns a singleton Name [it].
578
579         What you type                   The IO [HValue] that hscStmt returns
580         -------------                   ------------------------------------
581         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
582                                         bindings: [x,y,...]
583
584         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
585                                         bindings: [x,y,...]
586
587         expr (of IO type)       ==>     expr >>= \ v -> return [v]
588           [NB: result not printed]      bindings: [it]
589           
590
591         expr (of non-IO type, 
592           result showable)      ==>     let v = expr in print v >> return [v]
593                                         bindings: [it]
594
595         expr (of non-IO type, 
596           result not showable)  ==>     error
597
598 \begin{code}
599 hscStmt dflags hst hit pcs0 icontext stmt just_expr
600    =  do { maybe_stmt <- hscParseStmt dflags stmt
601         ; case maybe_stmt of
602              Nothing -> return (pcs0, Nothing)
603              Just parsed_stmt -> do {
604
605            let { notExprStmt (ExprStmt _ _ _) = False;
606                  notExprStmt _                = True 
607                };
608
609            if (just_expr && notExprStmt parsed_stmt)
610                 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
611                         return (pcs0, Nothing)
612                 else do {
613
614                 -- Rename it
615           (pcs1, print_unqual, maybe_renamed_stmt)
616                  <- renameStmt dflags hit hst pcs0 icontext parsed_stmt
617
618         ; case maybe_renamed_stmt of
619                 Nothing -> return (pcs0, Nothing)
620                 Just (bound_names, rn_stmt) -> do {
621
622                 -- Typecheck it
623           maybe_tc_return <- 
624             if just_expr 
625                 then case rn_stmt of { (ExprStmt e _ _, decls) -> 
626                      typecheckExpr dflags pcs1 hst (ic_type_env icontext)
627                            print_unqual iNTERACTIVE (e,decls) }
628                 else typecheckStmt dflags pcs1 hst (ic_type_env icontext)
629                            print_unqual iNTERACTIVE bound_names rn_stmt
630
631         ; case maybe_tc_return of
632                 Nothing -> return (pcs0, Nothing)
633                 Just (pcs2, tc_expr, bound_ids, ty) ->  do {
634
635                 -- Desugar it
636           ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
637         
638                 -- Flatten it
639         ; flat_expr <- flattenExpr dflags pcs2 hst ds_expr
640
641                 -- Simplify it
642         ; simpl_expr <- simplifyExpr dflags pcs2 hst flat_expr
643
644                 -- Tidy it (temporary, until coreSat does cloning)
645         ; tidy_expr <- tidyCoreExpr simpl_expr
646
647                 -- Prepare for codegen
648         ; prepd_expr <- corePrepExpr dflags tidy_expr
649
650                 -- Convert to BCOs
651         ; bcos <- coreExprToBCOs dflags prepd_expr
652
653         ; let
654                 -- Make all the bound ids "global" ids, now that
655                 -- they're notionally top-level bindings.  This is
656                 -- important: otherwise when we come to compile an expression
657                 -- using these ids later, the byte code generator will consider
658                 -- the occurrences to be free rather than global.
659              global_bound_ids = map globaliseId bound_ids;
660              globaliseId id   = setGlobalIdDetails id VanillaGlobal
661
662         ; return (pcs2, Just (global_bound_ids, ty, bcos))
663
664      }}}}}
665
666 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
667 hscParseStmt dflags str
668  = do --------------------------  Parser  ----------------
669       showPass dflags "Parser"
670       _scc_ "Parser"  do
671
672       buf <- stringToStringBuffer str
673
674       let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
675                            parrEF        = dopt Opt_PArr        dflags}
676           loc  = mkSrcLoc FSLIT("<interactive>") 1
677
678       case parseStmt buf (mkPState loc exts) of {
679
680         PFailed err -> do { hPutStrLn stderr (showSDoc err);
681 --      Not yet implemented in <4.11    freeStringBuffer buf;
682                             return Nothing };
683
684         -- no stmt: the line consisted of just space or comments
685         POk _ Nothing -> return Nothing;
686
687         POk _ (Just rdr_stmt) -> do {
688
689       --ToDo: can't free the string buffer until we've finished this
690       -- compilation sweep and all the identifiers have gone away.
691       --freeStringBuffer buf;
692       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
693       return (Just rdr_stmt)
694       }}
695 #endif
696 \end{code}
697
698 %************************************************************************
699 %*                                                                      *
700 \subsection{Getting information about an identifer}
701 %*                                                                      *
702 %************************************************************************
703
704 \begin{code}
705 #ifdef GHCI
706 hscThing -- like hscStmt, but deals with a single identifier
707   :: DynFlags
708   -> HomeSymbolTable
709   -> HomeIfaceTable
710   -> PersistentCompilerState    -- IN: persistent compiler state
711   -> InteractiveContext         -- Context for compiling
712   -> String                     -- The identifier
713   -> IO ( PersistentCompilerState,
714           [TyThing] )
715
716 hscThing dflags hst hit pcs0 ic str
717    = do maybe_rdr_name <- myParseIdentifier dflags str
718         case maybe_rdr_name of {
719           Nothing -> return (pcs0, []);
720           Just rdr_name -> do
721
722         -- if the identifier is a constructor (begins with an
723         -- upper-case letter), then we need to consider both
724         -- constructor and type class identifiers.
725         let rdr_names
726                 | occNameSpace occ == dataName = [ rdr_name, tccls_name ]
727                 | otherwise                    = [ rdr_name ]
728               where
729                 occ        = rdrNameOcc rdr_name
730                 tccls_occ  = setOccNameSpace occ tcClsName
731                 tccls_name = setRdrNameOcc rdr_name tccls_occ
732
733         (pcs, unqual, maybe_rn_result) <- 
734            renameRdrName dflags hit hst pcs0 ic rdr_names
735
736         case maybe_rn_result of {
737              Nothing -> return (pcs, []);
738              Just (names, decls) -> do {
739
740         maybe_pcs <- typecheckExtraDecls dflags pcs hst unqual
741                         iNTERACTIVE decls;
742
743         case maybe_pcs of {
744              Nothing -> return (pcs, []);
745              Just pcs ->
746                 let do_lookup n
747                         | isInternalName n = lookupNameEnv (ic_type_env ic) n
748                         | otherwise     = lookupType hst (pcs_PTE pcs) n
749                 
750                     maybe_ty_things = map do_lookup names
751                 in
752                 return (pcs, catMaybes maybe_ty_things) }
753         }}}
754
755 myParseIdentifier dflags str
756   = do buf <- stringToStringBuffer str
757  
758        let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
759                             parrEF        = dopt Opt_PArr        dflags}
760            loc  = mkSrcLoc FSLIT("<interactive>") 1
761
762        case parseIdentifier buf (mkPState loc exts) of
763
764           PFailed err -> do { hPutStrLn stderr (showSDoc err);
765                               freeStringBuffer buf;
766                               return Nothing }
767
768           POk _ rdr_name -> do { --should, but can't: freeStringBuffer buf;
769                                  return (Just rdr_name) }
770 #endif
771 \end{code}
772
773 %************************************************************************
774 %*                                                                      *
775 \subsection{Find all the things defined in a module}
776 %*                                                                      *
777 %************************************************************************
778
779 \begin{code}
780 #ifdef GHCI
781 hscModuleContents
782   :: DynFlags
783   -> HomeSymbolTable
784   -> HomeIfaceTable
785   -> PersistentCompilerState    -- IN: persistent compiler state
786   -> Module                     -- module to inspect
787   -> Bool                       -- grab just the exports, or the whole toplev
788   -> IO (PersistentCompilerState, Maybe [TyThing])
789
790 hscModuleContents dflags hst hit pcs0 mod exports_only = do {
791
792   -- slurp the interface if necessary
793   (pcs1, print_unqual, maybe_rn_stuff) 
794         <- slurpIface dflags hit hst pcs0 mod;
795
796   case maybe_rn_stuff of {
797         Nothing -> return (pcs0, Nothing);
798         Just (names, rn_decls) -> do {
799
800   -- Typecheck the declarations
801   maybe_pcs <-
802      typecheckExtraDecls dflags pcs1 hst print_unqual iNTERACTIVE rn_decls;
803
804   case maybe_pcs of {
805         Nothing   -> return (pcs1, Nothing);
806         Just pcs2 -> 
807
808   let { all_names 
809            | exports_only = names
810            | otherwise =
811              let { iface = fromJust (lookupModuleEnv hit mod);
812                    env   = fromJust (mi_globals iface);
813                    range = rdrEnvElts env;
814              } in
815              -- grab all the things from the global env that are locally def'd
816              nub [ n | elts <- range, GRE n LocalDef _ <- elts ];
817
818         pte = pcs_PTE pcs2;
819
820         ty_things = map (fromJust . lookupType hst pte) all_names;
821
822       } in
823
824   return (pcs2, Just ty_things)
825   }}}}
826 #endif
827 \end{code}
828
829 %************************************************************************
830 %*                                                                      *
831 \subsection{Initial persistent state}
832 %*                                                                      *
833 %************************************************************************
834
835 \begin{code}
836 initPersistentCompilerState :: IO PersistentCompilerState
837 initPersistentCompilerState 
838   = do prs <- initPersistentRenamerState
839        return (
840         PCS { pcs_PIT   = emptyIfaceTable,
841               pcs_PTE   = wiredInThingEnv,
842               pcs_insts = emptyInstEnv,
843               pcs_rules = emptyRuleBase,
844               pcs_PRS   = prs
845             }
846         )
847
848 initPersistentRenamerState :: IO PersistentRenamerState
849   = do us <- mkSplitUniqSupply 'r'
850        return (
851         PRS { prsOrig  = NameSupply { nsUniqs = us,
852                                       nsNames = initOrigNames,
853                                       nsIPs   = emptyFM },
854               prsDecls   = (emptyNameEnv, 0),
855               prsInsts   = (emptyBag, 0),
856               prsRules   = foldr add_rule (emptyBag, 0) builtinRules,
857               prsImpMods = emptyFM
858             }
859         )
860   where
861     add_rule (name,rule) (rules, n_rules)
862          = (gated_decl `consBag` rules, n_rules+1)
863         where
864            gated_decl = (gate_fn, (mod, IfaceRuleOut rdr_name rule))
865            mod        = nameModule name
866            rdr_name   = mkRdrOrig (moduleName mod) (nameOccName name)
867            gate_fn vis_fn = vis_fn name -- Load the rule whenever name is visible
868
869 initOrigNames :: FiniteMap (ModuleName,OccName) Name
870 initOrigNames 
871    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
872      where
873         grab names = foldl add emptyFM names
874         add env name 
875            = addToFM env (moduleName (nameModule name), nameOccName name) name
876 \end{code}