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