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