d2731054bfc4e3fefee55e724594c88093320c0a
[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 ( 
9         HscResult(..),
10         hscMain, newHscEnv, hscCmmFile, hscBufferFrontEnd
11 #ifdef GHCI
12         , hscStmt, hscTcExpr, hscKcType
13         , hscGetInfo, GetInfoResult
14         , compileExpr
15 #endif
16         ) where
17
18 #include "HsVersions.h"
19
20 #ifdef GHCI
21 import HsSyn            ( Stmt(..), LStmt, LHsExpr, LHsType )
22 import IfaceSyn         ( IfaceDecl, IfaceInst )
23 import CodeOutput       ( outputForeignStubs )
24 import ByteCodeGen      ( byteCodeGen, coreExprToBCOs )
25 import Linker           ( HValue, linkExpr )
26 import TidyPgm          ( tidyCoreExpr )
27 import CorePrep         ( corePrepExpr )
28 import Flattening       ( flattenExpr )
29 import TcRnDriver       ( tcRnStmt, tcRnExpr, tcRnGetInfo, tcRnType ) 
30 import RdrName          ( rdrNameOcc )
31 import OccName          ( occNameUserString )
32 import Type             ( Type )
33 import PrelNames        ( iNTERACTIVE )
34 import StringBuffer     ( stringToStringBuffer )
35 import Kind             ( Kind )
36 import Var              ( Id )
37 import CoreLint         ( lintUnfolding )
38 import DsMeta           ( templateHaskellNames )
39 import BasicTypes       ( Fixity )
40 import SrcLoc           ( SrcLoc, noSrcLoc )
41 #endif
42
43 import RdrName          ( RdrName )
44 import HsSyn            ( HsModule )
45 import SrcLoc           ( Located(..) )
46 import StringBuffer     ( hGetStringBuffer )
47 import Parser
48 import Lexer            ( P(..), ParseResult(..), mkPState )
49 import SrcLoc           ( mkSrcLoc )
50 import TcRnDriver       ( tcRnModule, tcRnExtCore )
51 import TcRnTypes        ( TcGblEnv )
52 import TcIface          ( typecheckIface )
53 import IfaceEnv         ( initNameCache )
54 import LoadIface        ( ifaceStats, initExternalPackageState )
55 import PrelInfo         ( wiredInThings, basicKnownKeyNames )
56 import RdrName          ( GlobalRdrEnv )
57 import MkIface          ( checkOldIface, mkIface )
58 import Desugar
59 import Flattening       ( flatten )
60 import SimplCore
61 import TidyPgm          ( tidyCorePgm )
62 import CorePrep         ( corePrepPgm )
63 import CoreToStg        ( coreToStg )
64 import Name             ( Name, NamedThing(..) )
65 import SimplStg         ( stg2stg )
66 import CodeGen          ( codeGen )
67 import CmmParse         ( parseCmmFile )
68 import CodeOutput       ( codeOutput )
69
70 import CmdLineOpts
71 import DriverPhases     ( isExtCoreFilename )
72 import ErrUtils
73 import UniqSupply       ( mkSplitUniqSupply )
74
75 import Outputable
76 import HscStats         ( ppSourceStats )
77 import HscTypes
78 import MkExternalCore   ( emitExternalCore )
79 import ParserCore
80 import ParserCoreUtils
81 import Module           ( Module, ModLocation(..), showModMsg )
82 import FastString
83 import Maybes           ( expectJust )
84 import StringBuffer     ( StringBuffer )
85 import Bag              ( unitBag, emptyBag )
86
87 import Monad            ( when )
88 import Maybe            ( isJust, fromJust )
89 import IO
90 import DATA_IOREF       ( newIORef, readIORef )
91 \end{code}
92
93
94 %************************************************************************
95 %*                                                                      *
96                 Initialisation
97 %*                                                                      *
98 %************************************************************************
99
100 \begin{code}
101 newHscEnv :: GhciMode -> DynFlags -> IO HscEnv
102 newHscEnv ghci_mode dflags
103   = do  { eps_var <- newIORef initExternalPackageState
104         ; us      <- mkSplitUniqSupply 'r'
105         ; nc_var  <- newIORef (initNameCache us knownKeyNames)
106         ; return (HscEnv { hsc_mode   = ghci_mode,
107                            hsc_dflags = dflags,
108                            hsc_HPT    = emptyHomePackageTable,
109                            hsc_EPS    = eps_var,
110                            hsc_NC     = nc_var } ) }
111                         
112
113 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
114                         -- where templateHaskellNames are defined
115 knownKeyNames = map getName wiredInThings 
116               ++ basicKnownKeyNames
117 #ifdef GHCI
118               ++ templateHaskellNames
119 #endif
120 \end{code}
121
122
123 %************************************************************************
124 %*                                                                      *
125                 The main compiler pipeline
126 %*                                                                      *
127 %************************************************************************
128
129 \begin{code}
130 data HscResult
131    -- Compilation failed
132    = HscFail
133
134    -- In IDE mode: we just do the static/dynamic checks
135    | HscChecked
136         (Located (HsModule RdrName))    -- parse tree
137         (Maybe TcGblEnv)                -- typechecker output, if succeeded
138
139    -- Concluded that it wasn't necessary
140    | HscNoRecomp ModDetails              -- new details (HomeSymbolTable additions)
141                  ModIface                -- new iface (if any compilation was done)
142
143    -- Did recompilation
144    | HscRecomp   ModDetails             -- new details (HomeSymbolTable additions)
145                  (Maybe GlobalRdrEnv)           
146                  ModIface               -- new iface (if any compilation was done)
147                  Bool                   -- stub_h exists
148                  Bool                   -- stub_c exists
149                  (Maybe CompiledByteCode)
150
151
152 -- What to do when we have compiler error or warning messages
153 type MessageAction = Messages -> IO ()
154
155         -- no errors or warnings; the individual passes
156         -- (parse/rename/typecheck) print messages themselves
157
158 hscMain
159   :: HscEnv
160   -> MessageAction              -- what to do with errors/warnings
161   -> Module
162   -> ModLocation                -- location info
163   -> Bool                       -- True <=> source unchanged
164   -> Bool                       -- True <=> have an object file (for msgs only)
165   -> Maybe ModIface             -- old interface, if available
166   -> IO HscResult
167
168 hscMain hsc_env msg_act mod location 
169         source_unchanged have_object maybe_old_iface
170  = do {
171       (recomp_reqd, maybe_checked_iface) <- 
172                 _scc_ "checkOldIface" 
173                 checkOldIface hsc_env mod 
174                               (ml_hi_file location)
175                               source_unchanged maybe_old_iface;
176
177       let no_old_iface = not (isJust maybe_checked_iface)
178           what_next | recomp_reqd || no_old_iface = hscRecomp 
179                     | otherwise                   = hscNoRecomp
180
181       ; what_next hsc_env msg_act have_object 
182                   mod location maybe_checked_iface
183       }
184
185
186 -- hscNoRecomp definitely expects to have the old interface available
187 hscNoRecomp hsc_env msg_act have_object 
188             mod location (Just old_iface)
189  | isOneShot (hsc_mode hsc_env)
190  = do {
191       compilationProgressMsg (hsc_dflags hsc_env) $
192         "compilation IS NOT required";
193       dumpIfaceStats hsc_env ;
194
195       let { bomb = panic "hscNoRecomp:OneShot" };
196       return (HscNoRecomp bomb bomb)
197       }
198  | otherwise
199  = do {
200       compilationProgressMsg (hsc_dflags hsc_env) $
201         ("Skipping  " ++ showModMsg have_object mod location);
202
203       new_details <- _scc_ "tcRnIface"
204                      typecheckIface hsc_env old_iface ;
205       dumpIfaceStats hsc_env ;
206
207       return (HscNoRecomp new_details old_iface)
208       }
209
210 hscRecomp hsc_env msg_act have_object 
211           mod location maybe_checked_iface
212  = do   {
213           -- what target are we shooting for?
214         ; let one_shot  = isOneShot (hsc_mode hsc_env)
215         ; let dflags    = hsc_dflags hsc_env
216         ; let toInterp  = dopt_HscLang dflags == HscInterpreted
217         ; let toCore    = isJust (ml_hs_file location) &&
218                           isExtCoreFilename (fromJust (ml_hs_file location))
219
220         ; when (not one_shot) $
221                 compilationProgressMsg dflags $
222                   ("Compiling " ++ showModMsg (not toInterp) mod location);
223                         
224         ; front_res <- if toCore then 
225                           hscCoreFrontEnd hsc_env msg_act location
226                        else 
227                           hscFileFrontEnd hsc_env msg_act location
228
229         ; case front_res of
230             Left flure -> return flure;
231             Right ds_result -> do {
232
233
234         -- OMITTED: 
235         -- ; seqList imported_modules (return ())
236
237             -------------------
238             -- FLATTENING
239             -------------------
240         ; flat_result <- _scc_ "Flattening"
241                          flatten hsc_env ds_result
242
243
244 {-      TEMP: need to review space-leak fixing here
245         NB: even the code generator can force one of the
246             thunks for constructor arguments, for newtypes in particular
247
248         ; let   -- Rule-base accumulated from imported packages
249              pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
250
251                 -- In one-shot mode, ZAP the external package state at
252                 -- this point, because we aren't going to need it from
253                 -- now on.  We keep the name cache, however, because
254                 -- tidyCore needs it.
255              pcs_middle 
256                  | one_shot  = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
257                  | otherwise = pcs_tc
258
259         ; pkg_rule_base `seq` pcs_middle `seq` return ()
260 -}
261
262         -- alive at this point:  
263         --      pcs_middle
264         --      flat_result
265         --      pkg_rule_base
266
267             -------------------
268             -- SIMPLIFY
269             -------------------
270         ; simpl_result <- _scc_ "Core2Core"
271                           core2core hsc_env flat_result
272
273             -------------------
274             -- TIDY
275             -------------------
276         ; tidy_result <- _scc_ "CoreTidy"
277                          tidyCorePgm hsc_env simpl_result
278
279         -- Emit external core
280         ; emitExternalCore dflags tidy_result
281
282         -- Alive at this point:  
283         --      tidy_result, pcs_final
284         --      hsc_env
285
286             -------------------
287             -- BUILD THE NEW ModIface and ModDetails
288             --  and emit external core if necessary
289             -- This has to happen *after* code gen so that the back-end
290             -- info has been set.  Not yet clear if it matters waiting
291             -- until after code output
292         ; new_iface <- _scc_ "MkFinalIface" 
293                         mkIface hsc_env location 
294                                 maybe_checked_iface tidy_result
295
296
297             -- Space leak reduction: throw away the new interface if
298             -- we're in one-shot mode; we won't be needing it any
299             -- more.
300         ; final_iface <-
301              if one_shot then return (error "no final iface")
302                          else return new_iface
303         ; let { final_globals | one_shot  = Nothing
304                               | otherwise = Just $! (mg_rdr_env tidy_result) }
305         ; final_globals `seq` return ()
306
307             -- Build the final ModDetails (except in one-shot mode, where
308             -- we won't need this information after compilation).
309         ; final_details <- 
310              if one_shot then return (error "no final details")
311                          else return $! ModDetails { 
312                                            md_types = mg_types tidy_result,
313                                            md_insts = mg_insts tidy_result,
314                                            md_rules = mg_rules tidy_result }
315
316             -------------------
317             -- CONVERT TO STG and COMPLETE CODE GENERATION
318         ; (stub_h_exists, stub_c_exists, maybe_bcos)
319                 <- hscBackEnd dflags tidy_result
320
321           -- And the answer is ...
322         ; dumpIfaceStats hsc_env
323
324         ; return (HscRecomp final_details
325                             final_globals
326                             final_iface
327                             stub_h_exists stub_c_exists
328                             maybe_bcos)
329          }}
330
331 hscCoreFrontEnd hsc_env msg_act location = do {
332             -------------------
333             -- PARSE
334             -------------------
335         ; inp <- readFile (expectJust "hscCoreFrontEnd:hspp" (ml_hspp_file location))
336         ; case parseCore inp 1 of
337             FailP s        -> putMsg s{-ToDo: wrong-} >> return (Left HscFail)
338             OkP rdr_module -> do {
339     
340             -------------------
341             -- RENAME and TYPECHECK
342             -------------------
343         ; (tc_msgs, maybe_tc_result) <- _scc_ "TypeCheck" 
344                               tcRnExtCore hsc_env rdr_module
345         ; msg_act tc_msgs
346         ; case maybe_tc_result of {
347              Nothing       -> return (Left  HscFail);
348              Just mod_guts -> return (Right mod_guts)
349                                         -- No desugaring to do!
350         }}}
351          
352
353 hscFileFrontEnd hsc_env msg_act location = do {
354             -------------------
355             -- PARSE
356             -------------------
357         ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) 
358                              (expectJust "hscFrontEnd:hspp" (ml_hspp_file location))
359
360         ; case maybe_parsed of {
361              Left err -> do { msg_act (unitBag err, emptyBag) ;
362                             ; return (Left HscFail) ;
363                             };
364              Right rdr_module -> hscFrontEnd hsc_env msg_act rdr_module
365     }}
366
367 -- Perform static/dynamic checks on the source code in a StringBuffer
368 -- This is a temporary solution: it'll read in interface files lazily, whereas
369 -- we probably want to use the compilation manager to load in all the modules
370 -- in a project.
371 hscBufferFrontEnd :: HscEnv -> StringBuffer -> MessageAction -> IO HscResult
372 hscBufferFrontEnd hsc_env buffer msg_act = do
373         let loc  = mkSrcLoc (mkFastString "*edit*") 1 0
374         showPass (hsc_dflags hsc_env) "Parser"
375         case unP parseModule (mkPState buffer loc (hsc_dflags hsc_env)) of
376                 PFailed span err -> do
377                    msg_act (emptyBag, unitBag (mkPlainErrMsg span err))
378                    return HscFail
379                 POk _ rdr_module -> do
380                    hscBufferTypecheck hsc_env rdr_module msg_act
381
382 hscBufferTypecheck hsc_env rdr_module msg_act = do
383         (tc_msgs, maybe_tc_result) <- _scc_ "Typecheck-Rename" 
384                                         tcRnModule hsc_env rdr_module
385         msg_act tc_msgs
386         case maybe_tc_result of
387             Nothing  -> return (HscChecked rdr_module Nothing)
388             Just r   -> return (HscChecked rdr_module (Just r))
389                                 -- space leak on rdr_module!
390
391
392 hscFrontEnd hsc_env msg_act rdr_module  = do {
393             -------------------
394             -- RENAME and TYPECHECK
395             -------------------
396         ; (tc_msgs, maybe_tc_result) <- _scc_ "Typecheck-Rename" 
397                                         tcRnModule hsc_env rdr_module
398         ; msg_act tc_msgs
399         ; case maybe_tc_result of {
400              Nothing -> return (Left HscFail);
401              Just tc_result -> do {
402
403             -------------------
404             -- DESUGAR
405             -------------------
406         ; (warns, maybe_ds_result) <- _scc_ "DeSugar" 
407                              deSugar hsc_env tc_result
408         ; msg_act (warns, emptyBag)
409         ; case maybe_ds_result of
410             Nothing        -> return (Left HscFail);
411             Just ds_result -> return (Right ds_result);
412         }}}
413
414 hscBackEnd dflags 
415     ModGuts{  -- This is the last use of the ModGuts in a compilation.
416               -- From now on, we just use the bits we need.
417         mg_module   = this_mod,
418         mg_binds    = core_binds,
419         mg_types    = type_env,
420         mg_dir_imps = dir_imps,
421         mg_foreign  = foreign_stubs,
422         mg_deps     = dependencies     }  = do {
423
424             -------------------
425             -- PREPARE FOR CODE GENERATION
426             -- Do saturation and convert to A-normal form
427   prepd_binds <- _scc_ "CorePrep"
428                  corePrepPgm dflags core_binds type_env;
429
430   case dopt_HscLang dflags of
431       HscNothing -> return (False, False, Nothing)
432
433       HscInterpreted ->
434 #ifdef GHCI
435         do  -----------------  Generate byte code ------------------
436             comp_bc <- byteCodeGen dflags prepd_binds type_env
437         
438             ------------------ Create f-x-dynamic C-side stuff ---
439             (istub_h_exists, istub_c_exists) 
440                <- outputForeignStubs dflags foreign_stubs
441             
442             return ( istub_h_exists, istub_c_exists, Just comp_bc )
443 #else
444         panic "GHC not compiled with interpreter"
445 #endif
446
447       other ->
448         do
449             -----------------  Convert to STG ------------------
450             (stg_binds, cost_centre_info) <- _scc_ "CoreToStg"
451                          myCoreToStg dflags this_mod prepd_binds        
452
453             ------------------  Code generation ------------------
454             abstractC <- _scc_ "CodeGen"
455                          codeGen dflags this_mod type_env foreign_stubs
456                                  dir_imps cost_centre_info stg_binds
457
458             ------------------  Code output -----------------------
459             (stub_h_exists, stub_c_exists)
460                      <- codeOutput dflags this_mod foreign_stubs 
461                                 dependencies abstractC
462
463             return (stub_h_exists, stub_c_exists, Nothing)
464    }
465
466
467 hscCmmFile :: DynFlags -> FilePath -> IO Bool
468 hscCmmFile dflags filename = do
469   maybe_cmm <- parseCmmFile dflags filename
470   case maybe_cmm of
471     Nothing -> return False
472     Just cmm -> do
473         codeOutput dflags no_mod NoStubs noDependencies [cmm]
474         return True
475   where
476         no_mod = panic "hscCmmFile: no_mod"
477
478
479 myParseModule dflags src_filename
480  = do --------------------------  Parser  ----------------
481       showPass dflags "Parser"
482       _scc_  "Parser" do
483       buf <- hGetStringBuffer src_filename
484
485       let loc  = mkSrcLoc (mkFastString src_filename) 1 0
486
487       case unP parseModule (mkPState buf loc dflags) of {
488
489         PFailed span err -> return (Left (mkPlainErrMsg span err));
490
491         POk _ rdr_module -> do {
492
493       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
494       
495       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
496                            (ppSourceStats False rdr_module) ;
497       
498       return (Right rdr_module)
499         -- ToDo: free the string buffer later.
500       }}
501
502
503 myCoreToStg dflags this_mod prepd_binds
504  = do 
505       stg_binds <- _scc_ "Core2Stg" 
506              coreToStg dflags prepd_binds
507
508       (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg" 
509              stg2stg dflags this_mod stg_binds
510
511       return (stg_binds2, cost_centre_info)
512 \end{code}
513
514
515 %************************************************************************
516 %*                                                                      *
517 \subsection{Compiling a do-statement}
518 %*                                                                      *
519 %************************************************************************
520
521 When the UnlinkedBCOExpr is linked you get an HValue of type
522         IO [HValue]
523 When you run it you get a list of HValues that should be 
524 the same length as the list of names; add them to the ClosureEnv.
525
526 A naked expression returns a singleton Name [it].
527
528         What you type                   The IO [HValue] that hscStmt returns
529         -------------                   ------------------------------------
530         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
531                                         bindings: [x,y,...]
532
533         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
534                                         bindings: [x,y,...]
535
536         expr (of IO type)       ==>     expr >>= \ v -> return [v]
537           [NB: result not printed]      bindings: [it]
538           
539
540         expr (of non-IO type, 
541           result showable)      ==>     let v = expr in print v >> return [v]
542                                         bindings: [it]
543
544         expr (of non-IO type, 
545           result not showable)  ==>     error
546
547 \begin{code}
548 #ifdef GHCI
549 hscStmt         -- Compile a stmt all the way to an HValue, but don't run it
550   :: HscEnv
551   -> InteractiveContext         -- Context for compiling
552   -> String                     -- The statement
553   -> IO (Maybe (InteractiveContext, [Name], HValue))
554
555 hscStmt hsc_env icontext stmt
556   = do  { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
557         ; case maybe_stmt of {
558              Nothing      -> return Nothing ;   -- Parse error
559              Just Nothing -> return Nothing ;   -- Empty line
560              Just (Just parsed_stmt) -> do {    -- The real stuff
561
562                 -- Rename and typecheck it
563           maybe_tc_result
564                  <- tcRnStmt hsc_env icontext parsed_stmt
565
566         ; case maybe_tc_result of {
567                 Nothing -> return Nothing ;
568                 Just (new_ic, bound_names, tc_expr) -> do {
569
570                 -- Then desugar, code gen, and link it
571         ; hval <- compileExpr hsc_env iNTERACTIVE 
572                               (ic_rn_gbl_env new_ic) 
573                               (ic_type_env new_ic)
574                               tc_expr
575
576         ; return (Just (new_ic, bound_names, hval))
577         }}}}}
578
579 hscTcExpr       -- Typecheck an expression (but don't run it)
580   :: HscEnv
581   -> InteractiveContext         -- Context for compiling
582   -> String                     -- The expression
583   -> IO (Maybe Type)
584
585 hscTcExpr hsc_env icontext expr
586   = do  { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
587         ; case maybe_stmt of {
588              Nothing      -> return Nothing ;   -- Parse error
589              Just (Just (L _ (ExprStmt expr _)))
590                         -> tcRnExpr hsc_env icontext expr ;
591              Just other -> do { errorMsg ("not an expression: `" ++ expr ++ "'") ;
592                                 return Nothing } ;
593              } }
594
595 hscKcType       -- Find the kind of a type
596   :: HscEnv
597   -> InteractiveContext         -- Context for compiling
598   -> String                     -- The type
599   -> IO (Maybe Kind)
600
601 hscKcType hsc_env icontext str
602   = do  { maybe_type <- hscParseType (hsc_dflags hsc_env) str
603         ; case maybe_type of {
604              Just ty    -> tcRnType hsc_env icontext ty ;
605              Just other -> do { errorMsg ("not an type: `" ++ str ++ "'") ;
606                                 return Nothing } ;
607              Nothing    -> return Nothing } }
608 \end{code}
609
610 \begin{code}
611 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
612 hscParseStmt = hscParseThing parseStmt
613
614 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
615 hscParseType = hscParseThing parseType
616
617 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
618 hscParseIdentifier = hscParseThing parseIdentifier
619
620 hscParseThing :: Outputable thing
621               => Lexer.P thing
622               -> DynFlags -> String
623               -> IO (Maybe thing)
624         -- Nothing => Parse error (message already printed)
625         -- Just x  => success
626 hscParseThing parser dflags str
627  = do showPass dflags "Parser"
628       _scc_ "Parser"  do
629
630       buf <- stringToStringBuffer str
631
632       let loc  = mkSrcLoc FSLIT("<interactive>") 1 0
633
634       case unP parser (mkPState buf loc dflags) of {
635
636         PFailed span err -> do { printError span err;
637                                  return Nothing };
638
639         POk _ thing -> do {
640
641       --ToDo: can't free the string buffer until we've finished this
642       -- compilation sweep and all the identifiers have gone away.
643       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
644       return (Just thing)
645       }}
646 #endif
647 \end{code}
648
649 %************************************************************************
650 %*                                                                      *
651 \subsection{Getting information about an identifer}
652 %*                                                                      *
653 %************************************************************************
654
655 \begin{code}
656 #ifdef GHCI
657 type GetInfoResult = (String, (IfaceDecl, Fixity, SrcLoc, [(IfaceInst,SrcLoc)]))
658
659 hscGetInfo -- like hscStmt, but deals with a single identifier
660   :: HscEnv
661   -> InteractiveContext         -- Context for compiling
662   -> String                     -- The identifier
663   -> IO [GetInfoResult]
664
665 hscGetInfo hsc_env ic str
666    = do maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
667         case maybe_rdr_name of {
668           Nothing -> return [];
669           Just (L _ rdr_name) -> do
670
671         maybe_tc_result <- tcRnGetInfo hsc_env ic rdr_name
672
673         let     -- str' is the the naked occurrence name
674                 -- after stripping off qualification and parens (+)
675            str' = occNameUserString (rdrNameOcc rdr_name)
676
677         case maybe_tc_result of {
678              Nothing     -> return [] ;
679              Just things -> return [(str', t) | t <- things]
680         }}
681 #endif
682 \end{code}
683
684 %************************************************************************
685 %*                                                                      *
686         Desugar, simplify, convert to bytecode, and link an expression
687 %*                                                                      *
688 %************************************************************************
689
690 \begin{code}
691 #ifdef GHCI
692 compileExpr :: HscEnv 
693             -> Module -> GlobalRdrEnv -> TypeEnv
694             -> LHsExpr Id
695             -> IO HValue
696
697 compileExpr hsc_env this_mod rdr_env type_env tc_expr
698   = do  { let { dflags  = hsc_dflags hsc_env ;
699                 lint_on = dopt Opt_DoCoreLinting dflags }
700               
701                 -- Desugar it
702         ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
703         
704                 -- Flatten it
705         ; flat_expr <- flattenExpr hsc_env ds_expr
706
707                 -- Simplify it
708         ; simpl_expr <- simplifyExpr dflags flat_expr
709
710                 -- Tidy it (temporary, until coreSat does cloning)
711         ; tidy_expr <- tidyCoreExpr simpl_expr
712
713                 -- Prepare for codegen
714         ; prepd_expr <- corePrepExpr dflags tidy_expr
715
716                 -- Lint if necessary
717                 -- ToDo: improve SrcLoc
718         ; if lint_on then 
719                 case lintUnfolding noSrcLoc [] prepd_expr of
720                    Just err -> pprPanic "compileExpr" err
721                    Nothing  -> return ()
722           else
723                 return ()
724
725                 -- Convert to BCOs
726         ; bcos <- coreExprToBCOs dflags prepd_expr
727
728                 -- link it
729         ; hval <- linkExpr hsc_env bcos
730
731         ; return hval
732      }
733 #endif
734 \end{code}
735
736
737 %************************************************************************
738 %*                                                                      *
739         Statistics on reading interfaces
740 %*                                                                      *
741 %************************************************************************
742
743 \begin{code}
744 dumpIfaceStats :: HscEnv -> IO ()
745 dumpIfaceStats hsc_env
746   = do  { eps <- readIORef (hsc_EPS hsc_env)
747         ; dumpIfSet (dump_if_trace || dump_rn_stats)
748                     "Interface statistics"
749                     (ifaceStats eps) }
750   where
751     dflags = hsc_dflags hsc_env
752     dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
753     dump_if_trace = dopt Opt_D_dump_if_trace dflags
754 \end{code}