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