Enumerate imports and remove dead code.
[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     ( newHscEnv, hscCmmFile
10     , hscFileCheck
11     , hscParseIdentifier
12 #ifdef GHCI
13     , hscStmt, hscTcExpr, hscKcType
14     , compileExpr
15 #endif
16     , hscCompileOneShot     -- :: Compiler HscStatus
17     , hscCompileMake        -- :: Compiler (HscStatus, ModIface, ModDetails)
18     , hscCompileInteractive -- :: Compiler (InteractiveStatus, ModIface, ModDetails)
19     , HscStatus (..)
20     , InteractiveStatus (..)
21     , HscChecked (..)
22     ) where
23
24 #include "HsVersions.h"
25
26 #ifdef GHCI
27 import HsSyn            ( Stmt(..), LHsExpr, LStmt, LHsType )
28 import Module           ( Module )
29 import CodeOutput       ( outputForeignStubs )
30 import ByteCodeGen      ( byteCodeGen, coreExprToBCOs )
31 import Linker           ( HValue, linkExpr )
32 import CoreTidy         ( tidyExpr )
33 import CorePrep         ( corePrepExpr )
34 import Flattening       ( flattenExpr )
35 import TcRnDriver       ( tcRnStmt, tcRnExpr, tcRnType ) 
36 import Type             ( Type )
37 import PrelNames        ( iNTERACTIVE )
38 import Kind             ( Kind )
39 import CoreLint         ( lintUnfolding )
40 import DsMeta           ( templateHaskellNames )
41 import SrcLoc           ( noSrcLoc )
42 import VarEnv           ( emptyTidyEnv )
43 #endif
44
45 import Var              ( Id )
46 import Module           ( emptyModuleEnv, ModLocation(..) )
47 import RdrName          ( GlobalRdrEnv, RdrName )
48 import HsSyn            ( HsModule, LHsBinds, HsGroup, LIE, LImportDecl )
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          ( deSugar )
62 import Flattening       ( flatten )
63 import SimplCore        ( core2core )
64 import TidyPgm          ( tidyProgram, mkBootModDetails )
65 import CorePrep         ( corePrepPgm )
66 import CoreToStg        ( coreToStg )
67 import TyCon            ( isDataTyCon )
68 import Packages         ( mkHomeModules )
69 import Name             ( Name, NamedThing(..) )
70 import SimplStg         ( stg2stg )
71 import CodeGen          ( codeGen )
72 import CmmParse         ( parseCmmFile )
73 import CodeOutput       ( codeOutput )
74
75 import DynFlags
76 import ErrUtils
77 import UniqSupply       ( mkSplitUniqSupply )
78
79 import Outputable
80 import HscStats         ( ppSourceStats )
81 import HscTypes
82 import MkExternalCore   ( emitExternalCore )
83 import ParserCore
84 import ParserCoreUtils
85 import FastString
86 import Maybes           ( expectJust )
87 import Bag              ( unitBag )
88 import Monad            ( when )
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                    --------------------------------
134                         The compilation proper
135                    --------------------------------
136
137
138 It's the task of the compilation proper to compile Haskell, hs-boot and
139 core files to either byte-code, hard-code (C, asm, Java, ect) or to
140 nothing at all (the module is still parsed and type-checked. This
141 feature is mostly used by IDE's and the likes).
142 Compilation can happen in either 'one-shot', 'make', or 'interactive'
143 mode. 'One-shot' mode targets hard-code, 'make' mode targets hard-code
144 and nothing, and 'interactive' mode targets byte-code. The modes are
145 kept separate because of their different types.
146 In 'one-shot' mode, we're only compiling a single file and can therefore
147 discard the new ModIface and ModDetails. This is also the reason it only
148 targets hard-code; compiling to byte-code or nothing doesn't make sense
149 when we discard the result. 'Make' mode is like 'one-shot' except that we
150 keep the resulting ModIface and ModDetails. 'Make' mode doesn't target
151 byte-code since that require us to return the newly compiled byte-code.
152 'Interactive' mode is similar to 'make' mode except that we return
153 the compiled byte-code together with the ModIface and ModDetails.
154 Trying to compile a hs-boot file to byte-code will result in a run-time
155 error. This is the only thing that isn't caught by the type-system.
156
157 \begin{code}
158
159 data HscChecked
160     = HscChecked
161         -- parsed
162         (Located (HsModule RdrName))
163         -- renamed
164         (Maybe (HsGroup Name,[LImportDecl Name],Maybe [LIE Name]))
165         -- typechecked
166         (Maybe (LHsBinds Id, GlobalRdrEnv, ModDetails))
167
168
169 -- Status of a compilation to hard-code or nothing.
170 data HscStatus
171     = HscNoRecomp
172     | HscRecomp  Bool -- Has stub files.
173                       -- This is a hack. We can't compile C files here
174                       -- since it's done in DriverPipeline. For now we
175                       -- just return True if we want the caller to compile
176                       -- it for us.
177
178 -- Status of a compilation to byte-code.
179 data InteractiveStatus
180     = InteractiveNoRecomp
181     | InteractiveRecomp Bool     -- Same as HscStatus
182                         CompiledByteCode
183
184 type NoRecomp result = HscEnv -> ModSummary -> Bool -> ModIface -> Maybe (Int,Int) -> IO result
185 type FrontEnd core = HscEnv -> ModSummary -> Maybe (Int,Int) -> IO (Maybe core)
186 type BackEnd core prepCore = HscEnv -> ModSummary -> Maybe ModIface -> core -> IO prepCore
187 type CodeGen prepCore result = HscEnv -> ModSummary -> prepCore -> IO result
188
189 type Compiler result =  HscEnv
190                      -> ModSummary
191                      -> Bool                -- True <=> source unchanged
192                      -> Bool                -- True <=> have an object file (for msgs only)
193                      -> Maybe ModIface      -- Old interface, if available
194                      -> Maybe (Int,Int)     -- Just (i,n) <=> module i of n (for msgs)
195                      -> IO (Maybe result)
196
197
198 -- This functions checks if recompilation is necessary and
199 -- then combines the FrontEnd, BackEnd and CodeGen to a
200 -- working compiler.
201 hscMkCompiler :: NoRecomp result         -- What to do when recompilation isn't required.
202               -> FrontEnd core
203               -> BackEnd core prepCore
204               -> CodeGen prepCore result
205               -> Compiler result
206 hscMkCompiler norecomp frontend backend codegen
207               hsc_env mod_summary source_unchanged
208               have_object mbOldIface mbModIndex
209     = do (recomp_reqd, mbCheckedIface)
210              <- {-# SCC "checkOldIface" #-}
211                 checkOldIface hsc_env mod_summary
212                               source_unchanged mbOldIface
213          case mbCheckedIface of 
214            Just iface | not recomp_reqd
215                -> do result <- norecomp hsc_env mod_summary have_object iface mbModIndex
216                      return (Just result)
217            _otherwise
218                -> do mbCore <- frontend hsc_env mod_summary mbModIndex
219                      case mbCore of
220                        Nothing
221                            -> return Nothing
222                        Just core
223                            -> do prepCore <- backend hsc_env mod_summary
224                                                      mbCheckedIface core
225                                  result <- codegen hsc_env mod_summary prepCore
226                                  return (Just result)
227
228 --------------------------------------------------------------
229 -- Compilers
230 --------------------------------------------------------------
231
232 -- Compile Haskell, boot and extCore in OneShot mode.
233 hscCompileOneShot :: Compiler HscStatus
234 hscCompileOneShot hsc_env mod_summary =
235     compiler hsc_env mod_summary
236     where mkComp = hscMkCompiler (norecompOneShot HscNoRecomp)
237           compiler
238               = case ms_hsc_src mod_summary of
239                 ExtCoreFile
240                     -> mkComp hscCoreFrontEnd hscNewBackEnd hscCodeGenOneShot
241 --        1         2         3         4         5         6         7         8          9
242                 HsSrcFile
243                     -> mkComp hscFileFrontEnd hscNewBackEnd hscCodeGenOneShot
244                 HsBootFile
245                     -> mkComp hscFileFrontEnd hscNewBootBackEnd
246                               (hscCodeGenConst (HscRecomp False))
247
248 -- Compile Haskell, boot and extCore in --make mode.
249 hscCompileMake :: Compiler (HscStatus, ModIface, ModDetails)
250 hscCompileMake hsc_env mod_summary
251     = compiler hsc_env mod_summary
252     where mkComp = hscMkCompiler norecompMake
253           backend = case hscTarget (hsc_dflags hsc_env) of
254                       HscNothing -> hscCodeGenNothing
255                       _other     -> hscCodeGenMake
256           compiler
257               = case ms_hsc_src mod_summary of
258                 ExtCoreFile
259                     -> mkComp hscCoreFrontEnd hscNewBackEnd backend
260                 HsSrcFile
261                     -> mkComp hscFileFrontEnd hscNewBackEnd backend
262                 HsBootFile
263                     -> mkComp hscFileFrontEnd hscNewBootBackEnd hscCodeGenIdentity
264
265
266 -- Compile Haskell, extCore to bytecode.
267 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
268 hscCompileInteractive hsc_env mod_summary =
269     hscMkCompiler norecompInteractive frontend hscNewBackEnd hscCodeGenInteractive
270                   hsc_env mod_summary
271     where frontend = case ms_hsc_src mod_summary of
272                        ExtCoreFile -> hscCoreFrontEnd
273                        HsSrcFile   -> hscFileFrontEnd
274                        HsBootFile  -> panic bootErrorMsg
275           bootErrorMsg = "Compiling a HsBootFile to bytecode doesn't make sense. " ++
276                          "Use 'hscCompileMake' instead."
277
278 --------------------------------------------------------------
279 -- NoRecomp handlers
280 --------------------------------------------------------------
281
282 norecompOneShot :: a -> NoRecomp a
283 norecompOneShot a hsc_env mod_summary 
284                 have_object old_iface
285                 mb_mod_index
286     = do compilationProgressMsg (hsc_dflags hsc_env) $
287            "compilation IS NOT required"
288          dumpIfaceStats hsc_env
289          return a
290
291 norecompMake :: NoRecomp (HscStatus, ModIface, ModDetails)
292 norecompMake = norecompWorker HscNoRecomp
293
294 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
295 norecompInteractive = norecompWorker InteractiveNoRecomp
296
297 norecompWorker :: a -> NoRecomp (a, ModIface, ModDetails)
298 norecompWorker a hsc_env mod_summary have_object
299              old_iface mb_mod_index
300     = do compilationProgressMsg (hsc_dflags hsc_env) $
301            (showModuleIndex mb_mod_index ++ 
302             "Skipping  " ++ showModMsg have_object mod_summary)
303          new_details <- {-# SCC "tcRnIface" #-}
304                         initIfaceCheck hsc_env $
305                         typecheckIface old_iface
306          dumpIfaceStats hsc_env
307          return (a, old_iface, new_details)
308
309 --------------------------------------------------------------
310 -- FrontEnds
311 --------------------------------------------------------------
312
313 hscCoreFrontEnd :: FrontEnd ModGuts
314 hscCoreFrontEnd hsc_env mod_summary mb_mod_index = do {
315             -------------------
316             -- PARSE
317             -------------------
318         ; inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
319         ; case parseCore inp 1 of
320             FailP s        -> do errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-})
321                                  return Nothing
322             OkP rdr_module -> do {
323     
324             -------------------
325             -- RENAME and TYPECHECK
326             -------------------
327         ; (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
328                               tcRnExtCore hsc_env rdr_module
329         ; printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
330         ; case maybe_tc_result of
331              Nothing       -> return Nothing
332              Just mod_guts -> return (Just mod_guts)    -- No desugaring to do!
333         }}
334          
335 hscFileFrontEnd :: FrontEnd ModGuts
336 hscFileFrontEnd hsc_env mod_summary mb_mod_index = do {
337             -------------------
338             -- DISPLAY PROGRESS MESSAGE
339             -------------------
340         ; let dflags    = hsc_dflags hsc_env
341               one_shot  = isOneShot (ghcMode dflags)
342               toInterp  = hscTarget dflags == HscInterpreted
343         ; when (not one_shot) $
344                  compilationProgressMsg dflags $
345                  (showModuleIndex mb_mod_index ++
346                   "Compiling " ++ showModMsg (not toInterp) mod_summary)
347                         
348             -------------------
349             -- PARSE
350             -------------------
351         ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
352               hspp_buf  = ms_hspp_buf  mod_summary
353
354         ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
355
356         ; case maybe_parsed of {
357              Left err -> do { printBagOfErrors dflags (unitBag err)
358                             ; return Nothing } ;
359              Right rdr_module -> do {
360
361             -------------------
362             -- RENAME and TYPECHECK
363             -------------------
364           (tc_msgs, maybe_tc_result) 
365                 <- {-# SCC "Typecheck-Rename" #-}
366                    tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
367
368         ; printErrorsAndWarnings dflags tc_msgs
369         ; case maybe_tc_result of {
370              Nothing -> return Nothing ;
371              Just tc_result -> do {
372
373             -------------------
374             -- DESUGAR
375             -------------------
376         ; (warns, maybe_ds_result) <- {-# SCC "DeSugar" #-}
377                              deSugar hsc_env tc_result
378         ; printBagOfWarnings dflags warns
379         ; return maybe_ds_result
380         }}}}}
381
382 --------------------------------------------------------------
383 -- BackEnds
384 --------------------------------------------------------------
385
386 hscNewBootBackEnd :: BackEnd ModGuts (HscStatus, ModIface, ModDetails)
387 hscNewBootBackEnd hsc_env mod_summary maybe_old_iface ds_result
388   = do details <- mkBootModDetails hsc_env ds_result
389        (new_iface, no_change) 
390            <- {-# SCC "MkFinalIface" #-}
391               mkIface hsc_env maybe_old_iface ds_result details
392        writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
393        -- And the answer is ...
394        dumpIfaceStats hsc_env
395        return (HscRecomp False, new_iface, details)
396
397 hscNewBackEnd :: BackEnd ModGuts (ModIface, ModDetails, CgGuts)
398 hscNewBackEnd hsc_env mod_summary maybe_old_iface ds_result
399   = do  {       -- OMITTED: 
400                 -- ; seqList imported_modules (return ())
401
402           let dflags    = hsc_dflags hsc_env
403
404             -------------------
405             -- FLATTENING
406             -------------------
407         ; flat_result <- {-# SCC "Flattening" #-}
408                          flatten hsc_env ds_result
409
410
411 {-      TEMP: need to review space-leak fixing here
412         NB: even the code generator can force one of the
413             thunks for constructor arguments, for newtypes in particular
414
415         ; let   -- Rule-base accumulated from imported packages
416              pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
417
418                 -- In one-shot mode, ZAP the external package state at
419                 -- this point, because we aren't going to need it from
420                 -- now on.  We keep the name cache, however, because
421                 -- tidyCore needs it.
422              pcs_middle 
423                  | one_shot  = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
424                  | otherwise = pcs_tc
425
426         ; pkg_rule_base `seq` pcs_middle `seq` return ()
427 -}
428
429         -- alive at this point:  
430         --      pcs_middle
431         --      flat_result
432         --      pkg_rule_base
433
434             -------------------
435             -- SIMPLIFY
436             -------------------
437         ; simpl_result <- {-# SCC "Core2Core" #-}
438                           core2core hsc_env flat_result
439
440             -------------------
441             -- TIDY
442             -------------------
443         ; (cg_guts, details) <- {-# SCC "CoreTidy" #-}
444                                  tidyProgram hsc_env simpl_result
445
446         -- Alive at this point:  
447         --      tidy_result, pcs_final
448         --      hsc_env
449
450             -------------------
451             -- BUILD THE NEW ModIface and ModDetails
452             --  and emit external core if necessary
453             -- This has to happen *after* code gen so that the back-end
454             -- info has been set.  Not yet clear if it matters waiting
455             -- until after code output
456         ; (new_iface, no_change)
457                 <- {-# SCC "MkFinalIface" #-}
458                    mkIface hsc_env maybe_old_iface simpl_result details
459
460         ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
461
462         -- Emit external core
463         ; emitExternalCore dflags cg_guts
464
465             -------------------
466             -- Return the prepared code.
467         ; return (new_iface, details, cg_guts)
468          }
469
470 --------------------------------------------------------------
471 -- Code generators
472 --------------------------------------------------------------
473
474 -- Don't output any code.
475 hscCodeGenNothing :: CodeGen (ModIface, ModDetails, CgGuts) (HscStatus, ModIface, ModDetails)
476 hscCodeGenNothing hsc_env mod_summary (iface, details, cgguts)
477     = return (HscRecomp False, iface, details)
478
479 -- Generate code and return both the new ModIface and the ModDetails.
480 hscCodeGenMake :: CodeGen (ModIface, ModDetails, CgGuts) (HscStatus, ModIface, ModDetails)
481 hscCodeGenMake hsc_env mod_summary (iface, details, cgguts)
482     = do hasStub <- hscCodeGenCompile hsc_env mod_summary cgguts
483          return (HscRecomp hasStub, iface, details)
484
485 -- Here we don't need the ModIface and ModDetails anymore.
486 hscCodeGenOneShot :: CodeGen (ModIface, ModDetails, CgGuts) HscStatus
487 hscCodeGenOneShot hsc_env mod_summary (_, _, cgguts)
488     = do hasStub <- hscCodeGenCompile hsc_env mod_summary cgguts
489          return (HscRecomp hasStub)
490
491 hscCodeGenCompile :: CodeGen CgGuts Bool
492 hscCodeGenCompile hsc_env mod_summary cgguts
493     = do let CgGuts{ -- This is the last use of the ModGuts in a compilation.
494                      -- From now on, we just use the bits we need.
495                      cg_module   = this_mod,
496                      cg_binds    = core_binds,
497                      cg_tycons   = tycons,
498                      cg_dir_imps = dir_imps,
499                      cg_foreign  = foreign_stubs,
500                      cg_home_mods = home_mods,
501                      cg_dep_pkgs = dependencies } = cgguts
502              dflags = hsc_dflags hsc_env
503              location = ms_location mod_summary
504              data_tycons = filter isDataTyCon tycons
505              -- cg_tycons includes newtypes, for the benefit of External Core,
506              -- but we don't generate any code for newtypes
507
508          -------------------
509          -- PREPARE FOR CODE GENERATION
510          -- Do saturation and convert to A-normal form
511          prepd_binds <- {-# SCC "CorePrep" #-}
512                         corePrepPgm dflags core_binds data_tycons ;
513          -----------------  Convert to STG ------------------
514          (stg_binds, cost_centre_info)
515              <- {-# SCC "CoreToStg" #-}
516                 myCoreToStg dflags home_mods this_mod prepd_binds       
517          ------------------  Code generation ------------------
518          abstractC <- {-# SCC "CodeGen" #-}
519                       codeGen dflags home_mods this_mod data_tycons
520                               foreign_stubs dir_imps cost_centre_info
521                               stg_binds
522          ------------------  Code output -----------------------
523          (stub_h_exists,stub_c_exists)
524              <- codeOutput dflags this_mod location foreign_stubs 
525                 dependencies abstractC
526          return stub_c_exists
527
528 hscCodeGenIdentity :: CodeGen a a
529 hscCodeGenIdentity hsc_env mod_summary a = return a
530
531 hscCodeGenConst :: b -> CodeGen a b
532 hscCodeGenConst b hsc_env mod_summary a = return b
533
534 hscCodeGenInteractive :: CodeGen (ModIface, ModDetails, CgGuts)
535                                  (InteractiveStatus, ModIface, ModDetails)
536 hscCodeGenInteractive hsc_env mod_summary (iface, details, cgguts)
537 #ifdef GHCI
538     = do let CgGuts{ -- This is the last use of the ModGuts in a compilation.
539                      -- From now on, we just use the bits we need.
540                      cg_module   = this_mod,
541                      cg_binds    = core_binds,
542                      cg_tycons   = tycons,
543                      cg_foreign  = foreign_stubs,
544                      cg_home_mods = home_mods,
545                      cg_dep_pkgs = dependencies } = cgguts
546              dflags = hsc_dflags hsc_env
547              location = ms_location mod_summary
548              data_tycons = filter isDataTyCon tycons
549              -- cg_tycons includes newtypes, for the benefit of External Core,
550              -- but we don't generate any code for newtypes
551
552          -------------------
553          -- PREPARE FOR CODE GENERATION
554          -- Do saturation and convert to A-normal form
555          prepd_binds <- {-# SCC "CorePrep" #-}
556                         corePrepPgm dflags core_binds data_tycons ;
557          -----------------  Generate byte code ------------------
558          comp_bc <- byteCodeGen dflags prepd_binds data_tycons
559          ------------------ Create f-x-dynamic C-side stuff ---
560          (istub_h_exists, istub_c_exists) 
561              <- outputForeignStubs dflags this_mod location foreign_stubs
562          return (InteractiveRecomp istub_c_exists comp_bc, iface, details)
563 #else
564     = panic "GHC not compiled with interpreter"
565 #endif
566
567
568 ------------------------------
569
570 hscFileCheck :: HscEnv -> ModSummary -> IO (Maybe HscChecked)
571 hscFileCheck hsc_env mod_summary = do {
572             -------------------
573             -- PARSE
574             -------------------
575         ; let dflags    = hsc_dflags hsc_env
576               hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
577               hspp_buf  = ms_hspp_buf  mod_summary
578
579         ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
580
581         ; case maybe_parsed of {
582              Left err -> do { printBagOfErrors dflags (unitBag err)
583                             ; return Nothing } ;
584              Right rdr_module -> do {
585
586             -------------------
587             -- RENAME and TYPECHECK
588             -------------------
589           (tc_msgs, maybe_tc_result) 
590                 <- _scc_ "Typecheck-Rename" 
591                    tcRnModule hsc_env (ms_hsc_src mod_summary) 
592                         True{-save renamed syntax-}
593                         rdr_module
594
595         ; printErrorsAndWarnings dflags tc_msgs
596         ; case maybe_tc_result of {
597              Nothing -> return (Just (HscChecked rdr_module Nothing Nothing));
598              Just tc_result -> do
599                 let md = ModDetails { 
600                                 md_types   = tcg_type_env tc_result,
601                                 md_exports = tcg_exports  tc_result,
602                                 md_insts   = tcg_insts    tc_result,
603                                 md_rules   = [panic "no rules"] }
604                                    -- Rules are CoreRules, not the
605                                    -- RuleDecls we get out of the typechecker
606                     rnInfo = do decl <- tcg_rn_decls tc_result
607                                 imports <- tcg_rn_imports tc_result
608                                 let exports = tcg_rn_exports tc_result
609                                 return (decl,imports,exports)
610                 return (Just (HscChecked rdr_module 
611                                    rnInfo
612                                    (Just (tcg_binds tc_result,
613                                           tcg_rdr_env tc_result,
614                                           md))))
615         }}}}
616
617
618 hscCmmFile :: DynFlags -> FilePath -> IO Bool
619 hscCmmFile dflags filename = do
620   maybe_cmm <- parseCmmFile dflags (mkHomeModules []) filename
621   case maybe_cmm of
622     Nothing -> return False
623     Just cmm -> do
624         codeOutput dflags no_mod no_loc NoStubs [] [cmm]
625         return True
626   where
627         no_mod = panic "hscCmmFile: no_mod"
628         no_loc = ModLocation{ ml_hs_file  = Just filename,
629                               ml_hi_file  = panic "hscCmmFile: no hi file",
630                               ml_obj_file = panic "hscCmmFile: no obj file" }
631
632
633 myParseModule dflags src_filename maybe_src_buf
634  =    --------------------------  Parser  ----------------
635       showPass dflags "Parser" >>
636       {-# SCC "Parser" #-} do
637
638         -- sometimes we already have the buffer in memory, perhaps
639         -- because we needed to parse the imports out of it, or get the 
640         -- module name.
641       buf <- case maybe_src_buf of
642                 Just b  -> return b
643                 Nothing -> hGetStringBuffer src_filename
644
645       let loc  = mkSrcLoc (mkFastString src_filename) 1 0
646
647       case unP parseModule (mkPState buf loc dflags) of {
648
649         PFailed span err -> return (Left (mkPlainErrMsg span err));
650
651         POk _ rdr_module -> do {
652
653       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
654       
655       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
656                            (ppSourceStats False rdr_module) ;
657       
658       return (Right rdr_module)
659         -- ToDo: free the string buffer later.
660       }}
661
662
663 myCoreToStg dflags home_mods this_mod prepd_binds
664  = do 
665       stg_binds <- {-# SCC "Core2Stg" #-}
666              coreToStg home_mods prepd_binds
667
668       (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
669              stg2stg dflags home_mods this_mod stg_binds
670
671       return (stg_binds2, cost_centre_info)
672 \end{code}
673
674
675 %************************************************************************
676 %*                                                                      *
677 \subsection{Compiling a do-statement}
678 %*                                                                      *
679 %************************************************************************
680
681 When the UnlinkedBCOExpr is linked you get an HValue of type
682         IO [HValue]
683 When you run it you get a list of HValues that should be 
684 the same length as the list of names; add them to the ClosureEnv.
685
686 A naked expression returns a singleton Name [it].
687
688         What you type                   The IO [HValue] that hscStmt returns
689         -------------                   ------------------------------------
690         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
691                                         bindings: [x,y,...]
692
693         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
694                                         bindings: [x,y,...]
695
696         expr (of IO type)       ==>     expr >>= \ v -> return [v]
697           [NB: result not printed]      bindings: [it]
698           
699
700         expr (of non-IO type, 
701           result showable)      ==>     let v = expr in print v >> return [v]
702                                         bindings: [it]
703
704         expr (of non-IO type, 
705           result not showable)  ==>     error
706
707 \begin{code}
708 #ifdef GHCI
709 hscStmt         -- Compile a stmt all the way to an HValue, but don't run it
710   :: HscEnv
711   -> String                     -- The statement
712   -> IO (Maybe (HscEnv, [Name], HValue))
713
714 hscStmt hsc_env stmt
715   = do  { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
716         ; case maybe_stmt of {
717              Nothing      -> return Nothing ;   -- Parse error
718              Just Nothing -> return Nothing ;   -- Empty line
719              Just (Just parsed_stmt) -> do {    -- The real stuff
720
721                 -- Rename and typecheck it
722           let icontext = hsc_IC hsc_env
723         ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
724
725         ; case maybe_tc_result of {
726                 Nothing -> return Nothing ;
727                 Just (new_ic, bound_names, tc_expr) -> do {
728
729                 -- Then desugar, code gen, and link it
730         ; hval <- compileExpr hsc_env iNTERACTIVE 
731                               (ic_rn_gbl_env new_ic) 
732                               (ic_type_env new_ic)
733                               tc_expr
734
735         ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
736         }}}}}
737
738 hscTcExpr       -- Typecheck an expression (but don't run it)
739   :: HscEnv
740   -> String                     -- The expression
741   -> IO (Maybe Type)
742
743 hscTcExpr hsc_env expr
744   = do  { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
745         ; let icontext = hsc_IC hsc_env
746         ; case maybe_stmt of {
747              Nothing      -> return Nothing ;   -- Parse error
748              Just (Just (L _ (ExprStmt expr _ _)))
749                         -> tcRnExpr hsc_env icontext expr ;
750              Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
751                                 return Nothing } ;
752              } }
753
754 hscKcType       -- Find the kind of a type
755   :: HscEnv
756   -> String                     -- The type
757   -> IO (Maybe Kind)
758
759 hscKcType hsc_env str
760   = do  { maybe_type <- hscParseType (hsc_dflags hsc_env) str
761         ; let icontext = hsc_IC hsc_env
762         ; case maybe_type of {
763              Just ty    -> tcRnType hsc_env icontext ty ;
764              Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an type:" <+> quotes (text str)) ;
765                                 return Nothing } ;
766              Nothing    -> return Nothing } }
767 #endif
768 \end{code}
769
770 \begin{code}
771 #ifdef GHCI
772 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
773 hscParseStmt = hscParseThing parseStmt
774
775 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
776 hscParseType = hscParseThing parseType
777 #endif
778
779 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
780 hscParseIdentifier = hscParseThing parseIdentifier
781
782 hscParseThing :: Outputable thing
783               => Lexer.P thing
784               -> DynFlags -> String
785               -> IO (Maybe thing)
786         -- Nothing => Parse error (message already printed)
787         -- Just x  => success
788 hscParseThing parser dflags str
789  = showPass dflags "Parser" >>
790       {-# SCC "Parser" #-} do
791
792       buf <- stringToStringBuffer str
793
794       let loc  = mkSrcLoc FSLIT("<interactive>") 1 0
795
796       case unP parser (mkPState buf loc dflags) of {
797
798         PFailed span err -> do { printError span err;
799                                  return Nothing };
800
801         POk _ thing -> do {
802
803       --ToDo: can't free the string buffer until we've finished this
804       -- compilation sweep and all the identifiers have gone away.
805       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
806       return (Just thing)
807       }}
808 \end{code}
809
810 %************************************************************************
811 %*                                                                      *
812         Desugar, simplify, convert to bytecode, and link an expression
813 %*                                                                      *
814 %************************************************************************
815
816 \begin{code}
817 #ifdef GHCI
818 compileExpr :: HscEnv 
819             -> Module -> GlobalRdrEnv -> TypeEnv
820             -> LHsExpr Id
821             -> IO HValue
822
823 compileExpr hsc_env this_mod rdr_env type_env tc_expr
824   = do  { let { dflags  = hsc_dflags hsc_env ;
825                 lint_on = dopt Opt_DoCoreLinting dflags }
826               
827                 -- Desugar it
828         ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
829         
830                 -- Flatten it
831         ; flat_expr <- flattenExpr hsc_env ds_expr
832
833                 -- Simplify it
834         ; simpl_expr <- simplifyExpr dflags flat_expr
835
836                 -- Tidy it (temporary, until coreSat does cloning)
837         ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
838
839                 -- Prepare for codegen
840         ; prepd_expr <- corePrepExpr dflags tidy_expr
841
842                 -- Lint if necessary
843                 -- ToDo: improve SrcLoc
844         ; if lint_on then 
845                 case lintUnfolding noSrcLoc [] prepd_expr of
846                    Just err -> pprPanic "compileExpr" err
847                    Nothing  -> return ()
848           else
849                 return ()
850
851                 -- Convert to BCOs
852         ; bcos <- coreExprToBCOs dflags prepd_expr
853
854                 -- link it
855         ; hval <- linkExpr hsc_env bcos
856
857         ; return hval
858      }
859 #endif
860 \end{code}
861
862
863 %************************************************************************
864 %*                                                                      *
865         Statistics on reading interfaces
866 %*                                                                      *
867 %************************************************************************
868
869 \begin{code}
870 dumpIfaceStats :: HscEnv -> IO ()
871 dumpIfaceStats hsc_env
872   = do  { eps <- readIORef (hsc_EPS hsc_env)
873         ; dumpIfSet (dump_if_trace || dump_rn_stats)
874                     "Interface statistics"
875                     (ifaceStats eps) }
876   where
877     dflags = hsc_dflags hsc_env
878     dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
879     dump_if_trace = dopt Opt_D_dump_if_trace dflags
880 \end{code}
881
882 %************************************************************************
883 %*                                                                      *
884         Progress Messages: Module i of n
885 %*                                                                      *
886 %************************************************************************
887
888 \begin{code}
889 showModuleIndex Nothing = ""
890 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
891     where
892         n_str = show n
893         i_str = show i
894         padded = replicate (length n_str - length i_str) ' ' ++ i_str
895 \end{code}
896