[project @ 2005-04-28 10:09:41 by simonpj]
[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          ( optTidyPgm, simpleTidyPgm )
65 import CorePrep         ( corePrepPgm )
66 import CoreToStg        ( coreToStg )
67 import Name             ( Name, NamedThing(..) )
68 import SimplStg         ( stg2stg )
69 import CodeGen          ( codeGen )
70 import CmmParse         ( parseCmmFile )
71 import CodeOutput       ( codeOutput )
72
73 import DynFlags
74 import DriverPhases     ( HscSource(..) )
75 import ErrUtils
76 import UniqSupply       ( mkSplitUniqSupply )
77
78 import Outputable
79 import HscStats         ( ppSourceStats )
80 import HscTypes
81 import MkExternalCore   ( emitExternalCore )
82 import ParserCore
83 import ParserCoreUtils
84 import FastString
85 import Maybes           ( expectJust )
86 import Bag              ( unitBag, emptyBag )
87 import Monad            ( when )
88 import Maybe            ( isJust )
89 import IO
90 import DATA_IOREF       ( newIORef, readIORef )
91 \end{code}
92
93
94 %************************************************************************
95 %*                                                                      *
96                 Initialisation
97 %*                                                                      *
98 %************************************************************************
99
100 \begin{code}
101 newHscEnv :: DynFlags -> IO HscEnv
102 newHscEnv dflags
103   = do  { eps_var <- newIORef initExternalPackageState
104         ; us      <- mkSplitUniqSupply 'r'
105         ; nc_var  <- newIORef (initNameCache us knownKeyNames)
106         ; fc_var  <- newIORef emptyModuleEnv
107         ; return (HscEnv { hsc_dflags = dflags,
108                            hsc_targets = [],
109                            hsc_mod_graph = [],
110                            hsc_IC     = emptyInteractiveContext,
111                            hsc_HPT    = emptyHomePackageTable,
112                            hsc_EPS    = eps_var,
113                            hsc_NC     = nc_var,
114                            hsc_FC     = fc_var } ) }
115                         
116
117 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
118                         -- where templateHaskellNames are defined
119 knownKeyNames = map getName wiredInThings 
120               ++ basicKnownKeyNames
121 #ifdef GHCI
122               ++ templateHaskellNames
123 #endif
124 \end{code}
125
126
127 %************************************************************************
128 %*                                                                      *
129                 The main compiler pipeline
130 %*                                                                      *
131 %************************************************************************
132
133 \begin{code}
134 data HscResult
135    -- Compilation failed
136    = HscFail
137
138    -- In IDE mode: we just do the static/dynamic checks
139    | HscChecked 
140         (Located (HsModule RdrName))                    -- parsed
141         (Maybe (HsGroup Name))                          -- renamed
142         (Maybe (LHsBinds Id, GlobalRdrEnv, ModDetails)) -- typechecked
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   -> Maybe (Int, Int)   -- Just (i,n) <=> module i of n (for msgs)
170   -> IO HscResult
171
172 hscMain hsc_env msg_act mod_summary
173         source_unchanged have_object maybe_old_iface
174         mb_mod_index
175  = do {
176       (recomp_reqd, maybe_checked_iface) <- 
177                 {-# SCC "checkOldIface" #-}
178                 checkOldIface hsc_env mod_summary 
179                               source_unchanged maybe_old_iface;
180
181       let no_old_iface = not (isJust maybe_checked_iface)
182           what_next | recomp_reqd || no_old_iface = hscRecomp 
183                     | otherwise                   = hscNoRecomp
184
185       ; what_next hsc_env msg_act mod_summary have_object 
186                   maybe_checked_iface
187                   mb_mod_index
188       }
189
190
191 ------------------------------
192 hscNoRecomp hsc_env msg_act mod_summary 
193             have_object (Just old_iface)
194             mb_mod_index
195  | isOneShot (ghcMode (hsc_dflags hsc_env))
196  = do {
197       compilationProgressMsg (hsc_dflags hsc_env) $
198         "compilation IS NOT required";
199       dumpIfaceStats hsc_env ;
200
201       let { bomb = panic "hscNoRecomp:OneShot" };
202       return (HscNoRecomp bomb bomb)
203       }
204  | otherwise
205  = do   { compilationProgressMsg (hsc_dflags hsc_env) $
206                 (showModuleIndex mb_mod_index ++ 
207                  "Skipping  " ++ showModMsg have_object mod_summary)
208
209         ; new_details <- {-# SCC "tcRnIface" #-}
210                          initIfaceCheck hsc_env $
211                          typecheckIface old_iface ;
212         ; dumpIfaceStats hsc_env
213
214         ; return (HscNoRecomp new_details old_iface)
215     }
216
217 hscNoRecomp hsc_env msg_act mod_summary 
218             have_object Nothing
219             mb_mod_index
220   = panic "hscNoRecomp" -- hscNoRecomp definitely expects to 
221                         -- have the old interface available
222
223 ------------------------------
224 hscRecomp hsc_env msg_act mod_summary
225           have_object maybe_old_iface
226           mb_mod_index
227  = case ms_hsc_src mod_summary of
228      HsSrcFile -> do 
229         front_res <- hscFileFrontEnd hsc_env msg_act mod_summary mb_mod_index
230         hscBackEnd hsc_env mod_summary maybe_old_iface front_res
231
232      HsBootFile -> do
233         front_res <- hscFileFrontEnd hsc_env msg_act 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 msg_act mod_summary
238         hscBackEnd hsc_env mod_summary maybe_old_iface front_res
239
240 hscCoreFrontEnd hsc_env msg_act 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        -> putMsg 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         ; msg_act 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 msg_act mod_summary mb_mod_index = do {
262             -------------------
263             -- DISPLAY PROGRESS MESSAGE
264             -------------------
265           let one_shot  = isOneShot (ghcMode (hsc_dflags hsc_env))
266         ; let dflags    = hsc_dflags hsc_env
267         ; let 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 (hsc_dflags hsc_env) hspp_file hspp_buf
280
281         ; case maybe_parsed of {
282              Left err -> do { msg_act (unitBag err, emptyBag)
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         ; msg_act 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         ; msg_act (warns, emptyBag)
304         ; return maybe_ds_result
305         }}}}}
306
307 ------------------------------
308
309 hscFileCheck :: HscEnv -> MessageAction -> ModSummary -> IO HscResult
310 hscFileCheck hsc_env msg_act mod_summary = do {
311             -------------------
312             -- PARSE
313             -------------------
314         ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
315               hspp_buf  = ms_hspp_buf  mod_summary
316
317         ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file hspp_buf
318
319         ; case maybe_parsed of {
320              Left err -> do { msg_act (unitBag err, emptyBag)
321                             ; return HscFail } ;
322              Right rdr_module -> do {
323
324             -------------------
325             -- RENAME and TYPECHECK
326             -------------------
327           (tc_msgs, maybe_tc_result) 
328                 <- _scc_ "Typecheck-Rename" 
329                    tcRnModule hsc_env (ms_hsc_src mod_summary) 
330                         True{-save renamed syntax-}
331                         rdr_module
332
333         ; msg_act tc_msgs
334         ; case maybe_tc_result of {
335              Nothing -> return (HscChecked rdr_module Nothing Nothing);
336              Just tc_result -> do
337                 let md = ModDetails { 
338                                 md_types   = tcg_type_env tc_result,
339                                 md_exports = tcg_exports  tc_result,
340                                 md_insts   = tcg_insts    tc_result,
341                                 md_rules   = [panic "no rules"] }
342                                    -- Rules are CoreRules, not the
343                                    -- RuleDecls we get out of the typechecker
344                 return (HscChecked rdr_module 
345                                    (tcg_rn_decls tc_result)
346                                    (Just (tcg_binds tc_result,
347                                           tcg_rdr_env tc_result,
348                                           md)))
349         }}}}
350
351 ------------------------------
352 hscBootBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
353 -- For hs-boot files, there's no code generation to do
354
355 hscBootBackEnd hsc_env mod_summary maybe_old_iface Nothing 
356   = return HscFail
357 hscBootBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result)
358   = do  { tidy_pgm <- simpleTidyPgm hsc_env ds_result
359
360         ; (new_iface, no_change) 
361                 <- {-# SCC "MkFinalIface" #-}
362                    mkIface hsc_env maybe_old_iface tidy_pgm
363
364         ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
365
366         ; let { final_details = ModDetails { md_types   = mg_types ds_result,
367                                              md_exports = mg_exports ds_result,
368                                              md_insts   = mg_insts ds_result,
369                                              md_rules   = mg_rules ds_result } }
370           -- And the answer is ...
371         ; dumpIfaceStats hsc_env
372
373         ; return (HscRecomp final_details
374                             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         ; let omit_prags = dopt Opt_OmitInterfacePragmas dflags
431         ; tidy_result <- {-# SCC "CoreTidy" #-}
432                          if omit_prags 
433                          then simpleTidyPgm hsc_env simpl_result
434                          else optTidyPgm    hsc_env simpl_result
435
436         -- Emit external core
437         ; emitExternalCore dflags tidy_result
438
439         -- Alive at this point:  
440         --      tidy_result, pcs_final
441         --      hsc_env
442
443             -------------------
444             -- BUILD THE NEW ModIface and ModDetails
445             --  and emit external core if necessary
446             -- This has to happen *after* code gen so that the back-end
447             -- info has been set.  Not yet clear if it matters waiting
448             -- until after code output
449         ; (new_iface, no_change) <- {-# SCC "MkFinalIface" #-}
450                                     mkIface hsc_env maybe_old_iface tidy_result
451
452         ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
453
454             -- Space leak reduction: throw away the new interface if
455             -- we're in one-shot mode; we won't be needing it any
456             -- more.
457         ; final_iface <- if one_shot then return (error "no final iface")
458                          else return new_iface
459
460             -- Build the final ModDetails (except in one-shot mode, where
461             -- we won't need this information after compilation).
462         ; final_details <- 
463              if one_shot then return (error "no final details")
464                          else return $! ModDetails { 
465                                            md_types   = mg_types tidy_result,
466                                            md_exports = mg_exports tidy_result,
467                                            md_insts   = mg_insts tidy_result,
468                                            md_rules   = mg_rules tidy_result }
469
470             -------------------
471             -- CONVERT TO STG and COMPLETE CODE GENERATION
472         ; (stub_h_exists, stub_c_exists, maybe_bcos)
473                 <- hscCodeGen dflags tidy_result
474
475           -- And the answer is ...
476         ; dumpIfaceStats hsc_env
477
478         ; return (HscRecomp final_details
479                             final_iface
480                             stub_h_exists stub_c_exists
481                             maybe_bcos)
482          }
483
484
485
486 hscCodeGen dflags 
487     ModGuts{  -- This is the last use of the ModGuts in a compilation.
488               -- From now on, we just use the bits we need.
489         mg_module   = this_mod,
490         mg_binds    = core_binds,
491         mg_types    = type_env,
492         mg_dir_imps = dir_imps,
493         mg_foreign  = foreign_stubs,
494         mg_deps     = dependencies     }  = do {
495
496             -------------------
497             -- PREPARE FOR CODE GENERATION
498             -- Do saturation and convert to A-normal form
499   prepd_binds <- {-# SCC "CorePrep" #-}
500                  corePrepPgm dflags core_binds type_env;
501
502   case hscTarget dflags of
503       HscNothing -> return (False, False, Nothing)
504
505       HscInterpreted ->
506 #ifdef GHCI
507         do  -----------------  Generate byte code ------------------
508             comp_bc <- byteCodeGen dflags prepd_binds type_env
509         
510             ------------------ Create f-x-dynamic C-side stuff ---
511             (istub_h_exists, istub_c_exists) 
512                <- outputForeignStubs dflags foreign_stubs
513             
514             return ( istub_h_exists, istub_c_exists, Just comp_bc )
515 #else
516         panic "GHC not compiled with interpreter"
517 #endif
518
519       other ->
520         do
521             -----------------  Convert to STG ------------------
522             (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-}
523                          myCoreToStg dflags this_mod prepd_binds        
524
525             ------------------  Code generation ------------------
526             abstractC <- {-# SCC "CodeGen" #-}
527                          codeGen dflags this_mod type_env foreign_stubs
528                                  dir_imps cost_centre_info stg_binds
529
530             ------------------  Code output -----------------------
531             (stub_h_exists, stub_c_exists)
532                      <- codeOutput dflags this_mod foreign_stubs 
533                                 dependencies abstractC
534
535             return (stub_h_exists, stub_c_exists, Nothing)
536    }
537
538
539 hscCmmFile :: DynFlags -> FilePath -> IO Bool
540 hscCmmFile dflags filename = do
541   maybe_cmm <- parseCmmFile dflags filename
542   case maybe_cmm of
543     Nothing -> return False
544     Just cmm -> do
545         codeOutput dflags no_mod NoStubs noDependencies [cmm]
546         return True
547   where
548         no_mod = panic "hscCmmFile: no_mod"
549
550
551 myParseModule dflags src_filename maybe_src_buf
552  =    --------------------------  Parser  ----------------
553       showPass dflags "Parser" >>
554       {-# SCC "Parser" #-} do
555
556         -- sometimes we already have the buffer in memory, perhaps
557         -- because we needed to parse the imports out of it, or get the 
558         -- module name.
559       buf <- case maybe_src_buf of
560                 Just b  -> return b
561                 Nothing -> hGetStringBuffer src_filename
562
563       let loc  = mkSrcLoc (mkFastString src_filename) 1 0
564
565       case unP parseModule (mkPState buf loc dflags) of {
566
567         PFailed span err -> return (Left (mkPlainErrMsg span err));
568
569         POk _ rdr_module -> do {
570
571       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
572       
573       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
574                            (ppSourceStats False rdr_module) ;
575       
576       return (Right rdr_module)
577         -- ToDo: free the string buffer later.
578       }}
579
580
581 myCoreToStg dflags this_mod prepd_binds
582  = do 
583       stg_binds <- {-# SCC "Core2Stg" #-}
584              coreToStg dflags prepd_binds
585
586       (stg_binds2, cost_centre_info) <- {-# SCC "Core2Stg" #-}
587              stg2stg dflags this_mod stg_binds
588
589       return (stg_binds2, cost_centre_info)
590 \end{code}
591
592
593 %************************************************************************
594 %*                                                                      *
595 \subsection{Compiling a do-statement}
596 %*                                                                      *
597 %************************************************************************
598
599 When the UnlinkedBCOExpr is linked you get an HValue of type
600         IO [HValue]
601 When you run it you get a list of HValues that should be 
602 the same length as the list of names; add them to the ClosureEnv.
603
604 A naked expression returns a singleton Name [it].
605
606         What you type                   The IO [HValue] that hscStmt returns
607         -------------                   ------------------------------------
608         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
609                                         bindings: [x,y,...]
610
611         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
612                                         bindings: [x,y,...]
613
614         expr (of IO type)       ==>     expr >>= \ v -> return [v]
615           [NB: result not printed]      bindings: [it]
616           
617
618         expr (of non-IO type, 
619           result showable)      ==>     let v = expr in print v >> return [v]
620                                         bindings: [it]
621
622         expr (of non-IO type, 
623           result not showable)  ==>     error
624
625 \begin{code}
626 #ifdef GHCI
627 hscStmt         -- Compile a stmt all the way to an HValue, but don't run it
628   :: HscEnv
629   -> String                     -- The statement
630   -> IO (Maybe (HscEnv, [Name], HValue))
631
632 hscStmt hsc_env stmt
633   = do  { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
634         ; case maybe_stmt of {
635              Nothing      -> return Nothing ;   -- Parse error
636              Just Nothing -> return Nothing ;   -- Empty line
637              Just (Just parsed_stmt) -> do {    -- The real stuff
638
639                 -- Rename and typecheck it
640           let icontext = hsc_IC hsc_env
641         ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
642
643         ; case maybe_tc_result of {
644                 Nothing -> return Nothing ;
645                 Just (new_ic, bound_names, tc_expr) -> do {
646
647                 -- Then desugar, code gen, and link it
648         ; hval <- compileExpr hsc_env iNTERACTIVE 
649                               (ic_rn_gbl_env new_ic) 
650                               (ic_type_env new_ic)
651                               tc_expr
652
653         ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
654         }}}}}
655
656 hscTcExpr       -- Typecheck an expression (but don't run it)
657   :: HscEnv
658   -> String                     -- The expression
659   -> IO (Maybe Type)
660
661 hscTcExpr hsc_env expr
662   = do  { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
663         ; let icontext = hsc_IC hsc_env
664         ; case maybe_stmt of {
665              Nothing      -> return Nothing ;   -- Parse error
666              Just (Just (L _ (ExprStmt expr _ _)))
667                         -> tcRnExpr hsc_env icontext expr ;
668              Just other -> do { errorMsg ("not an expression: `" ++ expr ++ "'") ;
669                                 return Nothing } ;
670              } }
671
672 hscKcType       -- Find the kind of a type
673   :: HscEnv
674   -> String                     -- The type
675   -> IO (Maybe Kind)
676
677 hscKcType hsc_env str
678   = do  { maybe_type <- hscParseType (hsc_dflags hsc_env) str
679         ; let icontext = hsc_IC hsc_env
680         ; case maybe_type of {
681              Just ty    -> tcRnType hsc_env icontext ty ;
682              Just other -> do { errorMsg ("not an type: `" ++ str ++ "'") ;
683                                 return Nothing } ;
684              Nothing    -> return Nothing } }
685 #endif
686 \end{code}
687
688 \begin{code}
689 #ifdef GHCI
690 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
691 hscParseStmt = hscParseThing parseStmt
692
693 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
694 hscParseType = hscParseThing parseType
695 #endif
696
697 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
698 hscParseIdentifier = hscParseThing parseIdentifier
699
700 hscParseThing :: Outputable thing
701               => Lexer.P thing
702               -> DynFlags -> String
703               -> IO (Maybe thing)
704         -- Nothing => Parse error (message already printed)
705         -- Just x  => success
706 hscParseThing parser dflags str
707  = showPass dflags "Parser" >>
708       {-# SCC "Parser" #-} do
709
710       buf <- stringToStringBuffer str
711
712       let loc  = mkSrcLoc FSLIT("<interactive>") 1 0
713
714       case unP parser (mkPState buf loc dflags) of {
715
716         PFailed span err -> do { printError span err;
717                                  return Nothing };
718
719         POk _ thing -> do {
720
721       --ToDo: can't free the string buffer until we've finished this
722       -- compilation sweep and all the identifiers have gone away.
723       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
724       return (Just thing)
725       }}
726 \end{code}
727
728 %************************************************************************
729 %*                                                                      *
730 \subsection{Getting information about an identifer}
731 %*                                                                      *
732 %************************************************************************
733
734 \begin{code}
735 #ifdef GHCI
736 hscGetInfo -- like hscStmt, but deals with a single identifier
737   :: HscEnv
738   -> String                     -- The identifier
739   -> IO [GetInfoResult]
740
741 hscGetInfo hsc_env str
742    = do maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
743         case maybe_rdr_name of {
744           Nothing -> return [];
745           Just (L _ rdr_name) -> do
746
747         maybe_tc_result <- tcRnGetInfo hsc_env (hsc_IC hsc_env) rdr_name
748
749         case maybe_tc_result of
750              Nothing     -> return []
751              Just things -> return things
752         }
753 #endif
754 \end{code}
755
756 %************************************************************************
757 %*                                                                      *
758         Desugar, simplify, convert to bytecode, and link an expression
759 %*                                                                      *
760 %************************************************************************
761
762 \begin{code}
763 #ifdef GHCI
764 compileExpr :: HscEnv 
765             -> Module -> GlobalRdrEnv -> TypeEnv
766             -> LHsExpr Id
767             -> IO HValue
768
769 compileExpr hsc_env this_mod rdr_env type_env tc_expr
770   = do  { let { dflags  = hsc_dflags hsc_env ;
771                 lint_on = dopt Opt_DoCoreLinting dflags }
772               
773                 -- Desugar it
774         ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
775         
776                 -- Flatten it
777         ; flat_expr <- flattenExpr hsc_env ds_expr
778
779                 -- Simplify it
780         ; simpl_expr <- simplifyExpr dflags flat_expr
781
782                 -- Tidy it (temporary, until coreSat does cloning)
783         ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
784
785                 -- Prepare for codegen
786         ; prepd_expr <- corePrepExpr dflags tidy_expr
787
788                 -- Lint if necessary
789                 -- ToDo: improve SrcLoc
790         ; if lint_on then 
791                 case lintUnfolding noSrcLoc [] prepd_expr of
792                    Just err -> pprPanic "compileExpr" err
793                    Nothing  -> return ()
794           else
795                 return ()
796
797                 -- Convert to BCOs
798         ; bcos <- coreExprToBCOs dflags prepd_expr
799
800                 -- link it
801         ; hval <- linkExpr hsc_env bcos
802
803         ; return hval
804      }
805 #endif
806 \end{code}
807
808
809 %************************************************************************
810 %*                                                                      *
811         Statistics on reading interfaces
812 %*                                                                      *
813 %************************************************************************
814
815 \begin{code}
816 dumpIfaceStats :: HscEnv -> IO ()
817 dumpIfaceStats hsc_env
818   = do  { eps <- readIORef (hsc_EPS hsc_env)
819         ; dumpIfSet (dump_if_trace || dump_rn_stats)
820                     "Interface statistics"
821                     (ifaceStats eps) }
822   where
823     dflags = hsc_dflags hsc_env
824     dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
825     dump_if_trace = dopt Opt_D_dump_if_trace dflags
826 \end{code}
827
828 %************************************************************************
829 %*                                                                      *
830         Progress Messages: Module i of n
831 %*                                                                      *
832 %************************************************************************
833
834 \begin{code}
835 showModuleIndex Nothing = ""
836 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
837     where
838         n_str = show n
839         i_str = show i
840         padded = replicate (length n_str - length i_str) ' ' ++ i_str
841 \end{code}
842