[project @ 2002-05-15 08:59:58 by chak]
[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                            ffiEF         = dopt Opt_FFI         dflags,
503                            withEF        = dopt Opt_With        dflags,
504                            parrEF        = dopt Opt_PArr        dflags}
505           loc  = mkSrcLoc (mkFastString src_filename) 1
506
507       case parseModule buf (mkPState loc exts) of {
508
509         PFailed err -> do { hPutStrLn stderr (showSDoc err);
510                             freeStringBuffer buf;
511                             return Nothing };
512
513         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
514
515       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
516       
517       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
518                            (ppSourceStats False rdr_module) ;
519       
520       return (Just rdr_module)
521         -- ToDo: free the string buffer later.
522       }}
523
524
525 myCoreToStg dflags this_mod tidy_binds
526  = do 
527       () <- coreBindsSize tidy_binds `seq` return ()
528       -- TEMP: the above call zaps some space usage allocated by the
529       -- simplifier, which for reasons I don't understand, persists
530       -- thoroughout code generation -- JRS
531       --
532       -- This is still necessary. -- SDM (10 Dec 2001)
533
534       stg_binds <- _scc_ "Core2Stg" 
535              coreToStg dflags tidy_binds
536
537       (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg" 
538              stg2stg dflags this_mod stg_binds
539
540       let env_rhs :: CgInfoEnv
541           env_rhs = mkNameEnv [ caf_info `seq` (idName bndr, CgInfo caf_info)
542                               | (bind,_) <- stg_binds2, 
543                                 let caf_info 
544                                      | stgBindHasCafRefs bind = MayHaveCafRefs
545                                      | otherwise              = NoCafRefs,
546                                 bndr <- stgBinders bind ]
547
548       return (stg_binds2, cost_centre_info, env_rhs)
549 \end{code}
550
551
552 %************************************************************************
553 %*                                                                      *
554 \subsection{Compiling a do-statement}
555 %*                                                                      *
556 %************************************************************************
557
558 \begin{code}
559 #ifdef GHCI
560 hscStmt
561   :: DynFlags
562   -> HomeSymbolTable    
563   -> HomeIfaceTable
564   -> PersistentCompilerState    -- IN: persistent compiler state
565   -> InteractiveContext         -- Context for compiling
566   -> String                     -- The statement
567   -> Bool                       -- just treat it as an expression
568   -> IO ( PersistentCompilerState, 
569           Maybe ( [Id], 
570                   Type, 
571                   UnlinkedBCOExpr) )
572 \end{code}
573
574 When the UnlinkedBCOExpr is linked you get an HValue of type
575         IO [HValue]
576 When you run it you get a list of HValues that should be 
577 the same length as the list of names; add them to the ClosureEnv.
578
579 A naked expression returns a singleton Name [it].
580
581         What you type                   The IO [HValue] that hscStmt returns
582         -------------                   ------------------------------------
583         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
584                                         bindings: [x,y,...]
585
586         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
587                                         bindings: [x,y,...]
588
589         expr (of IO type)       ==>     expr >>= \ v -> return [v]
590           [NB: result not printed]      bindings: [it]
591           
592
593         expr (of non-IO type, 
594           result showable)      ==>     let v = expr in print v >> return [v]
595                                         bindings: [it]
596
597         expr (of non-IO type, 
598           result not showable)  ==>     error
599
600 \begin{code}
601 hscStmt dflags hst hit pcs0 icontext stmt just_expr
602    =  do { maybe_stmt <- hscParseStmt dflags stmt
603         ; case maybe_stmt of
604              Nothing -> return (pcs0, Nothing)
605              Just parsed_stmt -> do {
606
607            let { notExprStmt (ExprStmt _ _ _) = False;
608                  notExprStmt _                = True 
609                };
610
611            if (just_expr && notExprStmt parsed_stmt)
612                 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
613                         return (pcs0, Nothing)
614                 else do {
615
616                 -- Rename it
617           (pcs1, print_unqual, maybe_renamed_stmt)
618                  <- renameStmt dflags hit hst pcs0 icontext parsed_stmt
619
620         ; case maybe_renamed_stmt of
621                 Nothing -> return (pcs0, Nothing)
622                 Just (bound_names, rn_stmt) -> do {
623
624                 -- Typecheck it
625           maybe_tc_return <- 
626             if just_expr 
627                 then case rn_stmt of { (ExprStmt e _ _, decls) -> 
628                      typecheckExpr dflags pcs1 hst (ic_type_env icontext)
629                            print_unqual iNTERACTIVE (e,decls) }
630                 else typecheckStmt dflags pcs1 hst (ic_type_env icontext)
631                            print_unqual iNTERACTIVE bound_names rn_stmt
632
633         ; case maybe_tc_return of
634                 Nothing -> return (pcs0, Nothing)
635                 Just (pcs2, tc_expr, bound_ids, ty) ->  do {
636
637                 -- Desugar it
638           ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
639         
640                 -- Flatten it
641         ; flat_expr <- flattenExpr dflags pcs2 hst ds_expr
642
643                 -- Simplify it
644         ; simpl_expr <- simplifyExpr dflags pcs2 hst flat_expr
645
646                 -- Tidy it (temporary, until coreSat does cloning)
647         ; tidy_expr <- tidyCoreExpr simpl_expr
648
649                 -- Prepare for codegen
650         ; prepd_expr <- corePrepExpr dflags tidy_expr
651
652                 -- Convert to BCOs
653         ; bcos <- coreExprToBCOs dflags prepd_expr
654
655         ; let
656                 -- Make all the bound ids "global" ids, now that
657                 -- they're notionally top-level bindings.  This is
658                 -- important: otherwise when we come to compile an expression
659                 -- using these ids later, the byte code generator will consider
660                 -- the occurrences to be free rather than global.
661              global_bound_ids = map globaliseId bound_ids;
662              globaliseId id   = setGlobalIdDetails id VanillaGlobal
663
664         ; return (pcs2, Just (global_bound_ids, ty, bcos))
665
666      }}}}}
667
668 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
669 hscParseStmt dflags str
670  = do --------------------------  Parser  ----------------
671       showPass dflags "Parser"
672       _scc_ "Parser"  do
673
674       buf <- stringToStringBuffer str
675
676       let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
677                            ffiEF         = dopt Opt_FFI         dflags,
678                            withEF        = dopt Opt_With        dflags,
679                            parrEF        = dopt Opt_PArr        dflags}
680           loc  = mkSrcLoc FSLIT("<interactive>") 1
681
682       case parseStmt buf (mkPState loc exts) of {
683
684         PFailed err -> do { hPutStrLn stderr (showSDoc err);
685 --      Not yet implemented in <4.11    freeStringBuffer buf;
686                             return Nothing };
687
688         -- no stmt: the line consisted of just space or comments
689         POk _ Nothing -> return Nothing;
690
691         POk _ (Just rdr_stmt) -> do {
692
693       --ToDo: can't free the string buffer until we've finished this
694       -- compilation sweep and all the identifiers have gone away.
695       --freeStringBuffer buf;
696       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
697       return (Just rdr_stmt)
698       }}
699 #endif
700 \end{code}
701
702 %************************************************************************
703 %*                                                                      *
704 \subsection{Getting information about an identifer}
705 %*                                                                      *
706 %************************************************************************
707
708 \begin{code}
709 #ifdef GHCI
710 hscThing -- like hscStmt, but deals with a single identifier
711   :: DynFlags
712   -> HomeSymbolTable
713   -> HomeIfaceTable
714   -> PersistentCompilerState    -- IN: persistent compiler state
715   -> InteractiveContext         -- Context for compiling
716   -> String                     -- The identifier
717   -> IO ( PersistentCompilerState,
718           [TyThing] )
719
720 hscThing dflags hst hit pcs0 ic str
721    = do maybe_rdr_name <- myParseIdentifier dflags str
722         case maybe_rdr_name of {
723           Nothing -> return (pcs0, []);
724           Just rdr_name -> do
725
726         -- if the identifier is a constructor (begins with an
727         -- upper-case letter), then we need to consider both
728         -- constructor and type class identifiers.
729         let rdr_names
730                 | occNameSpace occ == dataName = [ rdr_name, tccls_name ]
731                 | otherwise                    = [ rdr_name ]
732               where
733                 occ        = rdrNameOcc rdr_name
734                 tccls_occ  = setOccNameSpace occ tcClsName
735                 tccls_name = setRdrNameOcc rdr_name tccls_occ
736
737         (pcs, unqual, maybe_rn_result) <- 
738            renameRdrName dflags hit hst pcs0 ic rdr_names
739
740         case maybe_rn_result of {
741              Nothing -> return (pcs, []);
742              Just (names, decls) -> do {
743
744         maybe_pcs <- typecheckExtraDecls dflags pcs hst unqual
745                         iNTERACTIVE decls;
746
747         case maybe_pcs of {
748              Nothing -> return (pcs, []);
749              Just pcs ->
750                 let do_lookup n
751                         | isInternalName n = lookupNameEnv (ic_type_env ic) n
752                         | otherwise     = lookupType hst (pcs_PTE pcs) n
753                 
754                     maybe_ty_things = map do_lookup names
755                 in
756                 return (pcs, catMaybes maybe_ty_things) }
757         }}}
758
759 myParseIdentifier dflags str
760   = do buf <- stringToStringBuffer str
761  
762        let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
763                             ffiEF         = dopt Opt_FFI         dflags,
764                             withEF        = dopt Opt_With        dflags,
765                             parrEF        = dopt Opt_PArr        dflags}
766            loc  = mkSrcLoc FSLIT("<interactive>") 1
767
768        case parseIdentifier buf (mkPState loc exts) of
769
770           PFailed err -> do { hPutStrLn stderr (showSDoc err);
771                               freeStringBuffer buf;
772                               return Nothing }
773
774           POk _ rdr_name -> do { --should, but can't: freeStringBuffer buf;
775                                  return (Just rdr_name) }
776 #endif
777 \end{code}
778
779 %************************************************************************
780 %*                                                                      *
781 \subsection{Find all the things defined in a module}
782 %*                                                                      *
783 %************************************************************************
784
785 \begin{code}
786 #ifdef GHCI
787 hscModuleContents
788   :: DynFlags
789   -> HomeSymbolTable
790   -> HomeIfaceTable
791   -> PersistentCompilerState    -- IN: persistent compiler state
792   -> Module                     -- module to inspect
793   -> Bool                       -- grab just the exports, or the whole toplev
794   -> IO (PersistentCompilerState, Maybe [TyThing])
795
796 hscModuleContents dflags hst hit pcs0 mod exports_only = do {
797
798   -- slurp the interface if necessary
799   (pcs1, print_unqual, maybe_rn_stuff) 
800         <- slurpIface dflags hit hst pcs0 mod;
801
802   case maybe_rn_stuff of {
803         Nothing -> return (pcs0, Nothing);
804         Just (names, rn_decls) -> do {
805
806   -- Typecheck the declarations
807   maybe_pcs <-
808      typecheckExtraDecls dflags pcs1 hst print_unqual iNTERACTIVE rn_decls;
809
810   case maybe_pcs of {
811         Nothing   -> return (pcs1, Nothing);
812         Just pcs2 -> 
813
814   let { all_names 
815            | exports_only = names
816            | otherwise =
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}