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