[project @ 2002-08-29 15:44:11 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 MkExternalCore   ( emitExternalCore )
83 import ParserCore
84 import ParserCoreUtils
85 import FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
86 import OccName          ( OccName )
87 import Name             ( Name, nameModule, nameOccName, getName )
88 import NameEnv          ( emptyNameEnv, mkNameEnv )
89 import Module           ( Module )
90 import FastString
91 import Maybes           ( expectJust )
92 import Util             ( seqList )
93
94 import DATA_IOREF       ( newIORef, readIORef, writeIORef )
95 import UNSAFE_IO        ( unsafePerformIO )
96
97 import Monad            ( when )
98 import Maybe            ( isJust, fromJust )
99 import IO
100 \end{code}
101
102
103 %************************************************************************
104 %*                                                                      *
105 \subsection{The main compiler pipeline}
106 %*                                                                      *
107 %************************************************************************
108
109 \begin{code}
110 data HscResult
111    -- compilation failed
112    = HscFail     PersistentCompilerState -- updated PCS
113    -- concluded that it wasn't necessary
114    | HscNoRecomp PersistentCompilerState -- updated PCS
115                  ModDetails              -- new details (HomeSymbolTable additions)
116                  ModIface                -- new iface (if any compilation was done)
117    -- did recompilation
118    | HscRecomp   PersistentCompilerState -- updated PCS
119                  ModDetails              -- new details (HomeSymbolTable additions)
120                  ModIface                -- new iface (if any compilation was done)
121                  Bool                   -- stub_h exists
122                  Bool                   -- stub_c exists
123 #ifdef GHCI
124                  (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
125 #else
126                  (Maybe ())                      -- no interpreted code whatsoever
127 #endif
128
129         -- no errors or warnings; the individual passes
130         -- (parse/rename/typecheck) print messages themselves
131
132 hscMain
133   :: GhciMode
134   -> DynFlags
135   -> Module
136   -> ModuleLocation             -- location info
137   -> Bool                       -- True <=> source unchanged
138   -> Bool                       -- True <=> have an object file (for msgs only)
139   -> Maybe ModIface             -- old interface, if available
140   -> HomeSymbolTable            -- for home module ModDetails
141   -> HomeIfaceTable
142   -> PersistentCompilerState    -- IN: persistent compiler state
143   -> IO HscResult
144
145 hscMain ghci_mode dflags mod location source_unchanged have_object 
146         maybe_old_iface hst hit pcs
147  = {-# SCC "hscMain" #-}
148    do {
149       showPass dflags ("Checking old interface for hs = " 
150                         ++ show (ml_hs_file location)
151                         ++ ", hspp = " ++ show (ml_hspp_file location));
152
153       (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
154          <- _scc_ "checkOldIface"
155             checkOldIface ghci_mode dflags hit hst pcs mod (ml_hi_file location)
156                 source_unchanged maybe_old_iface;
157
158       if errs_found then
159          return (HscFail pcs_ch)
160       else do {
161
162       let no_old_iface = not (isJust maybe_checked_iface)
163           what_next | recomp_reqd || no_old_iface = hscRecomp 
164                     | otherwise                   = hscNoRecomp
165       ;
166       what_next ghci_mode dflags have_object mod location 
167                 maybe_checked_iface hst hit pcs_ch
168       }}
169
170
171 -- we definitely expect to have the old interface available
172 hscNoRecomp ghci_mode dflags have_object 
173             mod location (Just old_iface) hst hit pcs_ch
174  | ghci_mode == OneShot
175  = do {
176       when (verbosity dflags > 0) $
177           hPutStrLn stderr "compilation IS NOT required";
178       let { bomb = panic "hscNoRecomp:OneShot" };
179       return (HscNoRecomp pcs_ch bomb bomb)
180       }
181  | otherwise
182  = do {
183       when (verbosity dflags >= 1) $
184                 hPutStrLn stderr ("Skipping  " ++ 
185                         showModMsg have_object mod location);
186
187       -- CLOSURE
188       (pcs_cl, closure_errs, cl_hs_decls) 
189          <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
190       if closure_errs then 
191          return (HscFail pcs_cl) 
192       else do {
193
194       -- TYPECHECK
195       maybe_tc_result 
196         <- typecheckIface dflags pcs_cl hst old_iface cl_hs_decls;
197
198       case maybe_tc_result of {
199          Nothing -> return (HscFail pcs_cl);
200          Just (pcs_tc, new_details) ->
201
202       return (HscNoRecomp pcs_tc new_details old_iface)
203       }}}
204
205 hscRecomp ghci_mode dflags have_object 
206           mod location maybe_checked_iface hst hit pcs_ch
207  = do   {
208           -- what target are we shooting for?
209         ; let toInterp  = dopt_HscLang dflags == HscInterpreted
210         ; let toNothing = dopt_HscLang dflags == HscNothing
211         ; let toCore    = isJust (ml_hs_file location) &&
212                           isExtCore_file (fromJust (ml_hs_file location))
213
214         ; when (ghci_mode /= OneShot && verbosity dflags >= 1) $
215                 hPutStrLn stderr ("Compiling " ++ 
216                         showModMsg (not toInterp) mod location);
217                         
218         ; front_res <- 
219                 (if toCore then hscCoreFrontEnd else hscFrontEnd)
220                    ghci_mode dflags location hst hit pcs_ch
221         ; case front_res of
222             Left flure -> return flure;
223             Right (this_mod, rdr_module, 
224                    dont_discard, new_iface, 
225                    pcs_tc, ds_details, foreign_stuff) -> do {
226
227           let {
228             imported_module_names = 
229                 filter (/= gHC_PRIM_Name) $
230                 map ideclName (hsModuleImports rdr_module);
231
232             imported_modules =
233                 map (moduleNameToModule hit (pcs_PIT pcs_tc))
234                         imported_module_names;
235           }
236
237         -- force this out now, so we don't keep a hold of rdr_module or pcs_tc
238         ; seqList imported_modules (return ())
239
240             -------------------
241             -- FLATTENING
242             -------------------
243         ; flat_details
244              <- _scc_ "Flattening"
245                 flatten dflags pcs_tc hst ds_details
246
247         ; pcs_middle
248             <- _scc_ "pcs_middle"
249                 if ghci_mode == OneShot 
250                   then do init_pcs <- initPersistentCompilerState
251                           init_prs <- initPersistentRenamerState
252                           let 
253                               rules   = pcs_rules pcs_tc        
254                               orig_tc = prsOrig (pcs_PRS pcs_tc)
255                               new_prs = init_prs{ prsOrig=orig_tc }
256
257                           orig_tc `seq` rules `seq` new_prs `seq`
258                             return init_pcs{ pcs_PRS = new_prs,
259                                              pcs_rules = rules }
260                   else return pcs_tc
261
262 -- Should we remove bits of flat_details at this point?
263 --         ; flat_details <- case flat_details of
264 --                             ModDetails { md_binds = binds } ->
265 --                                 return ModDetails { md_binds = binds,
266 --                                                     md_rules = [],
267 --                                                     md_types = emptyTypeEnv,
268 --                                                     md_insts = [] }
269
270         -- alive at this point:  
271         --      pcs_middle
272         --      foreign_stuff
273         --      flat_details
274         --      imported_modules (seq'd)
275         --      new_iface
276
277             -------------------
278             -- SIMPLIFY
279             -------------------
280         ; simpl_details
281              <- _scc_     "Core2Core"
282                 core2core dflags pcs_middle hst dont_discard flat_details
283
284             -------------------
285             -- TIDY
286             -------------------
287         ; cg_info_ref <- newIORef Nothing ;
288         ; let cg_info :: CgInfoEnv
289               cg_info = unsafePerformIO $ do {
290                            maybe_cg_env <- readIORef cg_info_ref ;
291                            case maybe_cg_env of
292                              Just env -> return env
293                              Nothing  -> do { printError "Urk! Looked at CgInfo too early!";
294                                               return emptyNameEnv } }
295                 -- cg_info_ref will be filled in just after restOfCodeGeneration
296                 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
297
298         ; (pcs_simpl, tidy_details) 
299              <- _scc_ "CoreTidy"
300                 tidyCorePgm dflags this_mod pcs_middle cg_info simpl_details
301       
302         ; pcs_final <- if ghci_mode == OneShot then initPersistentCompilerState
303                                                else return pcs_simpl
304
305         -- alive at this point:  
306         --      tidy_details
307         --      new_iface               
308
309         ; emitExternalCore dflags new_iface tidy_details 
310
311         ; let final_details = tidy_details {md_binds = []} 
312         ; final_details `seq` return ()
313
314             -------------------
315             -- PREPARE FOR CODE GENERATION
316             -------------------
317               -- Do saturation and convert to A-normal form
318         ; prepd_details <- _scc_ "CorePrep" 
319                            corePrepPgm dflags tidy_details
320
321             -------------------
322             -- CONVERT TO STG and COMPLETE CODE GENERATION
323             -------------------
324         ; let
325             ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
326
327             local_tycons     = typeEnvTyCons  env_tc
328             local_classes    = typeEnvClasses env_tc
329
330             (h_code, c_code, headers, fe_binders) = foreign_stuff
331
332             -- turn the list of headers requested in foreign import
333             -- declarations into a string suitable for emission into generated
334             -- C code...
335             --
336             foreign_headers =   
337                 unlines 
338               . map (\fname -> "#include \"" ++ unpackFS fname ++ "\"")
339               . reverse 
340               $ headers
341
342           -- ...and add the string to the headers requested via command line
343           -- options 
344           --
345         ; fhdrs <- readIORef v_HCHeader
346         ; writeIORef v_HCHeader (fhdrs ++ foreign_headers)
347
348         ; (stub_h_exists, stub_c_exists, maybe_bcos, final_iface )
349            <- if toInterp
350 #ifdef GHCI
351                 then do 
352                     -----------------  Generate byte code ------------------
353                     (bcos,itbl_env) <- byteCodeGen dflags binds 
354                                         local_tycons local_classes
355
356                     -- Fill in the code-gen info
357                     writeIORef cg_info_ref (Just emptyNameEnv)
358
359                     ------------------ BUILD THE NEW ModIface ------------
360                     final_iface <- _scc_ "MkFinalIface" 
361                           mkFinalIface ghci_mode dflags location 
362                                    maybe_checked_iface new_iface tidy_details
363
364                     ------------------ Create f-x-dynamic C-side stuff ---
365                     (istub_h_exists, istub_c_exists) 
366                        <- outputForeignStubs dflags c_code h_code
367
368                     return ( istub_h_exists, istub_c_exists, 
369                              Just (bcos,itbl_env), final_iface )
370 #else
371                 then error "GHC not compiled with interpreter"
372 #endif
373
374                 else do
375                     -----------------  Convert to STG ------------------
376                     (stg_binds, cost_centre_info, stg_back_end_info) 
377                               <- _scc_ "CoreToStg"
378                                  myCoreToStg dflags this_mod binds
379                     
380                     -- Fill in the code-gen info for the earlier tidyCorePgm
381                     writeIORef cg_info_ref (Just stg_back_end_info)
382
383                     ------------------ BUILD THE NEW ModIface ------------
384                     final_iface <- _scc_ "MkFinalIface" 
385                           mkFinalIface ghci_mode dflags location 
386                                    maybe_checked_iface new_iface tidy_details
387                     if toNothing 
388                       then do
389                           return (False, False, Nothing, final_iface)
390                       else do
391                           ------------------  Code generation ------------------
392                           abstractC <- _scc_ "CodeGen"
393                                        codeGen dflags this_mod imported_modules
394                                                cost_centre_info fe_binders
395                                                local_tycons stg_binds
396                           
397                           ------------------  Code output -----------------------
398                           (stub_h_exists, stub_c_exists)
399                              <- codeOutput dflags this_mod [] --local_tycons
400                                    binds stg_binds
401                                    c_code h_code abstractC
402                               
403                           return (stub_h_exists, stub_c_exists, Nothing, final_iface)
404
405           -- and the answer is ...
406         ; return (HscRecomp pcs_final
407                             final_details
408                             final_iface
409                             stub_h_exists stub_c_exists
410                             maybe_bcos)
411          }}
412
413 hscCoreFrontEnd ghci_mode dflags location hst hit pcs_ch = do {
414             -------------------
415             -- PARSE
416             -------------------
417         ; inp <- readFile (expectJust "hscCoreFrontEnd:hspp" (ml_hspp_file location))
418         ; case parseCore inp 1 of
419             FailP s        -> hPutStrLn stderr s >> return (Left (HscFail pcs_ch));
420             OkP rdr_module -> do {
421         ; let this_mod = mkHomeModule (hsModuleName rdr_module)
422     
423             -------------------
424             -- RENAME
425             -------------------
426         ; (pcs_rn, print_unqual, maybe_rn_result) 
427              <- renameExtCore dflags hit hst pcs_ch this_mod rdr_module
428         ; case maybe_rn_result of {
429              Nothing -> return (Left (HscFail pcs_ch));
430              Just (dont_discard, new_iface, rn_decls) -> do {
431
432             -------------------
433             -- TYPECHECK
434             -------------------
435         ; maybe_tc_result 
436             <- _scc_ "TypeCheck" 
437                typecheckCoreModule dflags pcs_rn hst new_iface rn_decls
438         ; case maybe_tc_result of {
439              Nothing -> return (Left (HscFail pcs_ch));
440              Just (pcs_tc, tc_result) -> do {
441     
442             -------------------
443             -- DESUGAR
444             -------------------
445         ; (ds_details, foreign_stuff) <- deSugarCore tc_result
446         ; return (Right (this_mod, rdr_module, dont_discard, new_iface,
447                          pcs_tc, ds_details, foreign_stuff))
448         }}}}}}
449          
450
451 hscFrontEnd ghci_mode dflags location hst hit pcs_ch = do {
452             -------------------
453             -- PARSE
454             -------------------
455         ; maybe_parsed <- myParseModule dflags 
456                              (expectJust "hscRecomp:hspp" (ml_hspp_file location))
457         ; case maybe_parsed of {
458              Nothing -> return (Left (HscFail pcs_ch));
459              Just rdr_module -> do {
460         ; let this_mod = mkHomeModule (hsModuleName rdr_module)
461     
462             -------------------
463             -- RENAME
464             -------------------
465         ; (pcs_rn, print_unqual, maybe_rn_result) 
466              <- _scc_ "Rename" 
467                  renameModule dflags ghci_mode hit hst pcs_ch this_mod rdr_module
468         ; case maybe_rn_result of {
469              Nothing -> return (Left (HscFail pcs_ch));
470              Just (dont_discard, new_iface, rn_result) -> do {
471
472             -------------------
473             -- TYPECHECK
474             -------------------
475         ; maybe_tc_result 
476             <- _scc_ "TypeCheck" 
477                typecheckModule dflags pcs_rn hst print_unqual rn_result
478         ; case maybe_tc_result of {
479              Nothing -> return (Left (HscFail pcs_ch));
480              Just (pcs_tc, tc_result) -> do {
481     
482             -------------------
483             -- DESUGAR
484             -------------------
485         ; (ds_details, foreign_stuff) 
486              <- _scc_ "DeSugar" 
487                 deSugar dflags pcs_tc hst this_mod print_unqual tc_result
488         ; return (Right (this_mod, rdr_module, dont_discard, new_iface,
489                          pcs_tc, ds_details, foreign_stuff))
490         }}}}}}}
491
492
493 myParseModule dflags src_filename
494  = do --------------------------  Parser  ----------------
495       showPass dflags "Parser"
496       _scc_  "Parser" do
497       buf <- hGetStringBuffer src_filename
498
499       let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
500                            ffiEF         = dopt Opt_FFI         dflags,
501                            withEF        = dopt Opt_With        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                            ffiEF         = dopt Opt_FFI         dflags,
676                            withEF        = dopt Opt_With        dflags,
677                            parrEF        = dopt Opt_PArr        dflags}
678           loc  = mkSrcLoc FSLIT("<interactive>") 1
679
680       case parseStmt buf (mkPState loc exts) of {
681
682         PFailed err -> do { hPutStrLn stderr (showSDoc err);
683 --      Not yet implemented in <4.11    freeStringBuffer buf;
684                             return Nothing };
685
686         -- no stmt: the line consisted of just space or comments
687         POk _ Nothing -> return Nothing;
688
689         POk _ (Just rdr_stmt) -> do {
690
691       --ToDo: can't free the string buffer until we've finished this
692       -- compilation sweep and all the identifiers have gone away.
693       --freeStringBuffer buf;
694       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
695       return (Just rdr_stmt)
696       }}
697 #endif
698 \end{code}
699
700 %************************************************************************
701 %*                                                                      *
702 \subsection{Getting information about an identifer}
703 %*                                                                      *
704 %************************************************************************
705
706 \begin{code}
707 #ifdef GHCI
708 hscThing -- like hscStmt, but deals with a single identifier
709   :: DynFlags
710   -> HomeSymbolTable
711   -> HomeIfaceTable
712   -> PersistentCompilerState    -- IN: persistent compiler state
713   -> InteractiveContext         -- Context for compiling
714   -> String                     -- The identifier
715   -> IO ( PersistentCompilerState,
716           [TyThing] )
717
718 hscThing dflags hst hit pcs0 ic str
719    = do maybe_rdr_name <- myParseIdentifier dflags str
720         case maybe_rdr_name of {
721           Nothing -> return (pcs0, []);
722           Just rdr_name -> do
723
724         -- if the identifier is a constructor (begins with an
725         -- upper-case letter), then we need to consider both
726         -- constructor and type class identifiers.
727         let rdr_names
728                 | occNameSpace occ == dataName = [ rdr_name, tccls_name ]
729                 | otherwise                    = [ rdr_name ]
730               where
731                 occ        = rdrNameOcc rdr_name
732                 tccls_occ  = setOccNameSpace occ tcClsName
733                 tccls_name = setRdrNameOcc rdr_name tccls_occ
734
735         (pcs, unqual, maybe_rn_result) <- 
736            renameRdrName dflags hit hst pcs0 ic rdr_names
737
738         case maybe_rn_result of {
739              Nothing -> return (pcs, []);
740              Just (names, decls) -> do {
741
742         maybe_pcs <- typecheckExtraDecls dflags pcs hst unqual
743                         iNTERACTIVE decls;
744
745         case maybe_pcs of {
746              Nothing -> return (pcs, []);
747              Just pcs ->
748                 let do_lookup n
749                         | isInternalName n = lookupNameEnv (ic_type_env ic) n
750                         | otherwise     = lookupType hst (pcs_PTE pcs) n
751                 
752                     maybe_ty_things = map do_lookup names
753                 in
754                 return (pcs, catMaybes maybe_ty_things) }
755         }}}
756
757 myParseIdentifier dflags str
758   = do buf <- stringToStringBuffer str
759  
760        let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
761                             ffiEF         = dopt Opt_FFI         dflags,
762                             withEF        = dopt Opt_With        dflags,
763                             parrEF        = dopt Opt_PArr        dflags}
764            loc  = mkSrcLoc FSLIT("<interactive>") 1
765
766        case parseIdentifier buf (mkPState loc exts) of
767
768           PFailed err -> do { hPutStrLn stderr (showSDoc err);
769                               freeStringBuffer buf;
770                               return Nothing }
771
772           POk _ rdr_name -> do { --should, but can't: freeStringBuffer buf;
773                                  return (Just rdr_name) }
774 #endif
775 \end{code}
776
777 %************************************************************************
778 %*                                                                      *
779 \subsection{Find all the things defined in a module}
780 %*                                                                      *
781 %************************************************************************
782
783 \begin{code}
784 #ifdef GHCI
785 hscModuleContents
786   :: DynFlags
787   -> HomeSymbolTable
788   -> HomeIfaceTable
789   -> PersistentCompilerState    -- IN: persistent compiler state
790   -> Module                     -- module to inspect
791   -> Bool                       -- grab just the exports, or the whole toplev
792   -> IO (PersistentCompilerState, Maybe [TyThing])
793
794 hscModuleContents dflags hst hit pcs0 mod exports_only = do {
795
796   -- Slurp the interface if necessary (a home module will certainly
797   -- alraedy be loaded, but a package module might not be)
798   (pcs1, print_unqual, maybe_rn_stuff) 
799         <- slurpIface dflags hit hst pcs0 mod;
800
801   case maybe_rn_stuff of {
802         Nothing -> return (pcs0, Nothing);
803         Just (names, rn_decls) -> do {
804
805   -- Typecheck the declarations
806   maybe_pcs <-
807      typecheckExtraDecls dflags pcs1 hst print_unqual iNTERACTIVE rn_decls;
808
809   case maybe_pcs of {
810         Nothing   -> return (pcs1, Nothing);
811         Just pcs2 -> 
812
813   let { all_names 
814            | exports_only = names
815            | otherwise =        -- Invariant; we only have (not exports_only) 
816                                 -- for a home module so it must already be in the HIT
817              let { iface = fromJust (lookupModuleEnv hit mod);
818                    env   = fromJust (mi_globals iface);
819                    range = rdrEnvElts env;
820              } in
821              -- grab all the things from the global env that are locally def'd
822              nub [ n | elts <- range, GRE n LocalDef _ <- elts ];
823
824         pte = pcs_PTE pcs2;
825
826         ty_things = map (fromJust . lookupType hst pte) all_names;
827
828       } in
829
830   return (pcs2, Just ty_things)
831   }}}}
832 #endif
833 \end{code}
834
835 %************************************************************************
836 %*                                                                      *
837 \subsection{Initial persistent state}
838 %*                                                                      *
839 %************************************************************************
840
841 \begin{code}
842 initPersistentCompilerState :: IO PersistentCompilerState
843 initPersistentCompilerState 
844   = do prs <- initPersistentRenamerState
845        return (
846         PCS { pcs_PIT   = emptyIfaceTable,
847               pcs_PTE   = wiredInThingEnv,
848               pcs_insts = emptyInstEnv,
849               pcs_rules = emptyRuleBase,
850               pcs_PRS   = prs
851             }
852         )
853
854 initPersistentRenamerState :: IO PersistentRenamerState
855   = do us <- mkSplitUniqSupply 'r'
856        return (
857         PRS { prsOrig  = NameSupply { nsUniqs = us,
858                                       nsNames = initOrigNames,
859                                       nsIPs   = emptyFM },
860               prsDecls   = (emptyNameEnv, 0),
861               prsInsts   = (emptyBag, 0),
862               prsRules   = foldr add_rule (emptyBag, 0) builtinRules,
863               prsImpMods = emptyFM
864             }
865         )
866   where
867     add_rule (name,rule) (rules, n_rules)
868          = (gated_decl `consBag` rules, n_rules+1)
869         where
870            gated_decl = (gate_fn, (mod, IfaceRuleOut rdr_name rule))
871            mod        = nameModule name
872            rdr_name   = mkRdrOrig (moduleName mod) (nameOccName name)
873            gate_fn vis_fn = vis_fn name -- Load the rule whenever name is visible
874
875 initOrigNames :: FiniteMap (ModuleName,OccName) Name
876 initOrigNames 
877    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
878      where
879         grab names = foldl add emptyFM names
880         add env name 
881            = addToFM env (moduleName (nameModule name), nameOccName name) name
882 \end{code}