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