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