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