7236620b90a9d6d07ca52c3302bc90845f146e76
[ghc-hetmet.git] / ghc / compiler / main / HscMain.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
3 %
4
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
6
7 \begin{code}
8 module HscMain ( 
9         HscResult(..),
10         hscMain, newHscEnv, hscCmmFile, 
11         hscFileCheck,
12         hscParseIdentifier,
13 #ifdef GHCI
14         hscStmt, hscTcExpr, hscKcType,
15         compileExpr,
16 #endif
17         ) where
18
19 #include "HsVersions.h"
20
21 #ifdef GHCI
22 import HsSyn            ( Stmt(..), LHsExpr, LStmt, LHsType )
23 import Module           ( Module )
24 import CodeOutput       ( outputForeignStubs )
25 import ByteCodeGen      ( byteCodeGen, coreExprToBCOs )
26 import Linker           ( HValue, linkExpr )
27 import CoreTidy         ( tidyExpr )
28 import CorePrep         ( corePrepExpr )
29 import Flattening       ( flattenExpr )
30 import TcRnDriver       ( tcRnStmt, tcRnExpr, tcRnType ) 
31 import Type             ( Type )
32 import PrelNames        ( iNTERACTIVE )
33 import Kind             ( Kind )
34 import CoreLint         ( lintUnfolding )
35 import DsMeta           ( templateHaskellNames )
36 import SrcLoc           ( noSrcLoc )
37 import VarEnv           ( emptyTidyEnv )
38 #endif
39
40 import Var              ( Id )
41 import Module           ( emptyModuleEnv, ModLocation(..) )
42 import RdrName          ( GlobalRdrEnv, RdrName )
43 import HsSyn            ( HsModule, LHsBinds, HsGroup, LIE, LImportDecl )
44 import SrcLoc           ( Located(..) )
45 import StringBuffer     ( hGetStringBuffer, stringToStringBuffer )
46 import Parser
47 import Lexer            ( P(..), ParseResult(..), mkPState )
48 import SrcLoc           ( mkSrcLoc )
49 import TcRnDriver       ( tcRnModule, tcRnExtCore )
50 import TcIface          ( typecheckIface )
51 import TcRnMonad        ( initIfaceCheck, TcGblEnv(..) )
52 import IfaceEnv         ( initNameCache )
53 import LoadIface        ( ifaceStats, initExternalPackageState )
54 import PrelInfo         ( wiredInThings, basicKnownKeyNames )
55 import MkIface          ( checkOldIface, mkIface, writeIfaceFile )
56 import Desugar
57 import Flattening       ( flatten )
58 import SimplCore
59 import TidyPgm          ( tidyProgram, mkBootModDetails )
60 import CorePrep         ( corePrepPgm )
61 import CoreToStg        ( coreToStg )
62 import TyCon            ( isDataTyCon )
63 import Packages         ( mkHomeModules )
64 import Name             ( Name, NamedThing(..) )
65 import SimplStg         ( stg2stg )
66 import CodeGen          ( codeGen )
67 import CmmParse         ( parseCmmFile )
68 import CodeOutput       ( codeOutput )
69
70 import DynFlags
71 import ErrUtils
72 import Util
73 import UniqSupply       ( mkSplitUniqSupply )
74
75 import Outputable
76 import HscStats         ( ppSourceStats )
77 import HscTypes
78 import MkExternalCore   ( emitExternalCore )
79 import ParserCore
80 import ParserCoreUtils
81 import FastString
82 import Maybes           ( expectJust )
83 import Bag              ( unitBag )
84 import Monad            ( when )
85 import Maybe            ( isJust )
86 import IO
87 import DATA_IOREF       ( newIORef, readIORef )
88 \end{code}
89
90
91 %************************************************************************
92 %*                                                                      *
93                 Initialisation
94 %*                                                                      *
95 %************************************************************************
96
97 \begin{code}
98 newHscEnv :: DynFlags -> IO HscEnv
99 newHscEnv dflags
100   = do  { eps_var <- newIORef initExternalPackageState
101         ; us      <- mkSplitUniqSupply 'r'
102         ; nc_var  <- newIORef (initNameCache us knownKeyNames)
103         ; fc_var  <- newIORef emptyModuleEnv
104         ; return (HscEnv { hsc_dflags = dflags,
105                            hsc_targets = [],
106                            hsc_mod_graph = [],
107                            hsc_IC     = emptyInteractiveContext,
108                            hsc_HPT    = emptyHomePackageTable,
109                            hsc_EPS    = eps_var,
110                            hsc_NC     = nc_var,
111                            hsc_FC     = fc_var } ) }
112                         
113
114 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
115                         -- where templateHaskellNames are defined
116 knownKeyNames = map getName wiredInThings 
117               ++ basicKnownKeyNames
118 #ifdef GHCI
119               ++ templateHaskellNames
120 #endif
121 \end{code}
122
123
124 %************************************************************************
125 %*                                                                      *
126                 The main compiler pipeline
127 %*                                                                      *
128 %************************************************************************
129
130                    --------------------------------
131                         The compilation proper
132                    --------------------------------
133
134
135 It's the task of the compilation proper to compile Haskell, hs-boot and
136 core files to either byte-code, hard-code (C, asm, Java, ect) or to
137 nothing at all (the module is still parsed and type-checked. This
138 feature is mostly used by IDE's and the likes).
139 Compilation can happen in either 'one-shot', 'make', or 'interactive'
140 mode. 'One-shot' mode targets hard-code, 'make' mode targets hard-code
141 and nothing, and 'interactive' mode targets byte-code. The modes are
142 kept separate because of their different types.
143 In 'one-shot' mode, we're only compiling a single file and can therefore
144 discard the new ModIface and ModDetails. This is also the reason it only
145 targets hard-code; compiling to byte-code or nothing doesn't make sense
146 when we discard the result. 'Make' mode is like 'one-shot' except that we
147 keep the resulting ModIface and ModDetails. 'Make' mode doesn't target
148 byte-code since that require us to return the newly compiled byte-code.
149 'Interactive' mode is similar to 'make' mode except that we return
150 the compiled byte-code together with the ModIface and ModDetails.
151 Trying to compile a hs-boot file to byte-code will result in a run-time
152 error. This is the only thing that isn't caught by the type-system.
153
154 \begin{code}
155 data HscResult
156    -- Compilation failed
157    = HscFail
158
159    -- In IDE mode: we just do the static/dynamic checks
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    -- Concluded that it wasn't necessary
169    | HscNoRecomp ModDetails              -- new details (HomeSymbolTable additions)
170                  ModIface                -- new iface (if any compilation was done)
171
172    -- Did recompilation
173    | HscRecomp   ModDetails             -- new details (HomeSymbolTable additions)
174                  ModIface               -- new iface (if any compilation was done)
175                  Bool                   -- stub_h exists
176                  Bool                   -- stub_c exists
177                  (Maybe CompiledByteCode)
178
179
180 -- What to do when we have compiler error or warning messages
181 type MessageAction = Messages -> IO ()
182
183
184 --------------------------------------------------------------
185 -- Exterimental code start.
186 --------------------------------------------------------------
187
188 data HscStatus
189     = NewHscNoRecomp
190     | NewHscRecomp  Bool         -- Has stub files.
191                                  -- This is a hack. We can't compile C files here
192                                  -- since it's done in DriverPipeline. For now we
193                                  -- just return True if we want the caller to compile
194                                  -- it for us.
195
196 data InteractiveStatus
197     = InteractiveNoRecomp
198     | InteractiveRecomp Bool     -- Same as HscStatus
199                         CompiledByteCode
200
201 type NoRecomp result = HscEnv -> ModSummary -> Bool -> ModIface -> Maybe (Int,Int) -> IO result
202 type FrontEnd core = HscEnv -> ModSummary -> Maybe (Int,Int) -> IO (Maybe core)
203 type BackEnd core prepCore = HscEnv -> ModSummary -> Maybe ModIface -> core -> IO prepCore
204 type CodeGen prepCore result = HscEnv -> ModSummary -> prepCore -> IO result
205
206 type Compiler result =  HscEnv
207                      -> ModSummary
208                      -> Bool                -- True <=> source unchanged
209                      -> Bool                -- True <=> have an object file (for msgs only)
210                      -> Maybe ModIface      -- Old interface, if available
211                      -> Maybe (Int,Int)     -- Just (i,n) <=> module i of n (for msgs)
212                      -> IO (Maybe result)
213
214
215 hscMkCompiler :: NoRecomp result         -- What to do when recompilation isn't required.
216               -> FrontEnd core
217               -> BackEnd core prepCore
218               -> CodeGen prepCore result
219               -> Compiler result
220 hscMkCompiler norecomp frontend backend codegen
221               hsc_env mod_summary source_unchanged
222               have_object mbOldIface mbModIndex
223     = do (recomp_reqd, mbCheckedIface)
224              <- {-# SCC "checkOldIface" #-}
225                 checkOldIface hsc_env mod_summary
226                               source_unchanged mbOldIface
227          case mbCheckedIface of 
228            Just iface | not recomp_reqd
229                -> do result <- norecomp hsc_env mod_summary have_object iface mbModIndex
230                      return (Just result)
231            _otherwise
232                -> do mbCore <- frontend hsc_env mod_summary mbModIndex
233                      case mbCore of
234                        Nothing
235                            -> return Nothing
236                        Just core
237                            -> do prepCore <- backend hsc_env mod_summary
238                                                      mbCheckedIface core
239                                  result <- codegen hsc_env mod_summary prepCore
240                                  return (Just result)
241
242 -- Compile Haskell, boot and extCore in OneShot mode.
243 hscCompileOneShot :: Compiler HscStatus
244 hscCompileOneShot hsc_env mod_summary =
245     compiler hsc_env mod_summary
246     where mkComp = hscMkCompiler (norecompOneShot NewHscNoRecomp)
247           compiler
248               = case ms_hsc_src mod_summary of
249                 ExtCoreFile
250                     -> mkComp hscCoreFrontEnd hscNewBackEnd hscCodeGenOneShot
251 --        1         2         3         4         5         6         7         8          9
252                 HsSrcFile
253                     -> mkComp hscFileFrontEnd hscNewBackEnd hscCodeGenOneShot
254                 HsBootFile
255                     -> mkComp hscFileFrontEnd hscNewBootBackEnd
256                               (hscCodeGenConst (NewHscRecomp False))
257
258 -- Compile Haskell, boot and extCore in --make mode.
259 hscCompileMake :: Compiler (HscStatus, ModIface, ModDetails)
260 hscCompileMake hsc_env mod_summary
261     = compiler hsc_env mod_summary
262     where mkComp = hscMkCompiler norecompMake
263           backend = case hscTarget (hsc_dflags hsc_env) of
264                       HscNothing -> hscCodeGenSimple (\(i, d, g) -> (NewHscRecomp False, i, d))
265                       _other     -> hscCodeGenMake
266           compiler
267               = case ms_hsc_src mod_summary of
268                 ExtCoreFile
269                     -> mkComp hscCoreFrontEnd hscNewBackEnd backend
270                 HsSrcFile
271                     -> mkComp hscFileFrontEnd hscNewBackEnd backend
272                 HsBootFile
273                     -> mkComp hscFileFrontEnd hscNewBootBackEnd hscCodeGenIdentity
274
275
276 -- Compile Haskell, extCore to bytecode.
277 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
278 hscCompileInteractive hsc_env mod_summary =
279     hscMkCompiler norecompInteractive frontend hscNewBackEnd hscCodeGenInteractive
280                   hsc_env mod_summary
281     where frontend = case ms_hsc_src mod_summary of
282                        ExtCoreFile -> hscCoreFrontEnd
283                        HsSrcFile   -> hscFileFrontEnd
284                        HsBootFile  -> panic bootErrorMsg
285           bootErrorMsg = "Compiling a HsBootFile to bytecode doesn't make sense. " ++
286                          "Use 'hscCompileMake' instead."
287
288 norecompOneShot :: a -> NoRecomp a
289 norecompOneShot a hsc_env mod_summary 
290                 have_object old_iface
291                 mb_mod_index
292     = do compilationProgressMsg (hsc_dflags hsc_env) $
293            "compilation IS NOT required"
294          dumpIfaceStats hsc_env
295          return a
296
297 norecompMake :: NoRecomp (HscStatus, ModIface, ModDetails)
298 norecompMake = norecompWorker NewHscNoRecomp
299
300 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
301 norecompInteractive = norecompWorker InteractiveNoRecomp
302
303 norecompWorker :: a -> NoRecomp (a, ModIface, ModDetails)
304 norecompWorker a hsc_env mod_summary have_object
305              old_iface mb_mod_index
306     = do compilationProgressMsg (hsc_dflags hsc_env) $
307            (showModuleIndex mb_mod_index ++ 
308             "Skipping  " ++ showModMsg have_object mod_summary)
309          new_details <- {-# SCC "tcRnIface" #-}
310                         initIfaceCheck hsc_env $
311                         typecheckIface old_iface
312          dumpIfaceStats hsc_env
313          return (a, old_iface, new_details)
314
315 hscNewBootBackEnd :: BackEnd ModGuts (HscStatus, ModIface, ModDetails)
316 hscNewBootBackEnd hsc_env mod_summary maybe_old_iface ds_result
317   = do details <- mkBootModDetails hsc_env ds_result
318        (new_iface, no_change) 
319            <- {-# SCC "MkFinalIface" #-}
320               mkIface hsc_env maybe_old_iface ds_result details
321        writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
322        -- And the answer is ...
323        dumpIfaceStats hsc_env
324        return (NewHscRecomp False, new_iface, details)
325
326 hscNewBackEnd :: BackEnd ModGuts (ModIface, ModDetails, CgGuts)
327 hscNewBackEnd hsc_env mod_summary maybe_old_iface ds_result
328   = do  {       -- OMITTED: 
329                 -- ; seqList imported_modules (return ())
330
331           let dflags    = hsc_dflags hsc_env
332
333             -------------------
334             -- FLATTENING
335             -------------------
336         ; flat_result <- {-# SCC "Flattening" #-}
337                          flatten hsc_env ds_result
338
339
340 {-      TEMP: need to review space-leak fixing here
341         NB: even the code generator can force one of the
342             thunks for constructor arguments, for newtypes in particular
343
344         ; let   -- Rule-base accumulated from imported packages
345              pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
346
347                 -- In one-shot mode, ZAP the external package state at
348                 -- this point, because we aren't going to need it from
349                 -- now on.  We keep the name cache, however, because
350                 -- tidyCore needs it.
351              pcs_middle 
352                  | one_shot  = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
353                  | otherwise = pcs_tc
354
355         ; pkg_rule_base `seq` pcs_middle `seq` return ()
356 -}
357
358         -- alive at this point:  
359         --      pcs_middle
360         --      flat_result
361         --      pkg_rule_base
362
363             -------------------
364             -- SIMPLIFY
365             -------------------
366         ; simpl_result <- {-# SCC "Core2Core" #-}
367                           core2core hsc_env flat_result
368
369             -------------------
370             -- TIDY
371             -------------------
372         ; (cg_guts, details) <- {-# SCC "CoreTidy" #-}
373                                  tidyProgram hsc_env simpl_result
374
375         -- Alive at this point:  
376         --      tidy_result, pcs_final
377         --      hsc_env
378
379             -------------------
380             -- BUILD THE NEW ModIface and ModDetails
381             --  and emit external core if necessary
382             -- This has to happen *after* code gen so that the back-end
383             -- info has been set.  Not yet clear if it matters waiting
384             -- until after code output
385         ; (new_iface, no_change)
386                 <- {-# SCC "MkFinalIface" #-}
387                    mkIface hsc_env maybe_old_iface simpl_result details
388
389         ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
390
391         -- Emit external core
392         ; emitExternalCore dflags cg_guts
393
394             -------------------
395             -- Return the prepared code.
396         ; return (new_iface, details, cg_guts)
397          }
398
399 -- Don't output any code.
400 hscCodeGenNothing :: CodeGen (ModIface, ModDetails, CgGuts) (HscStatus, ModIface, ModDetails)
401 hscCodeGenNothing hsc_env mod_summary (iface, details, cgguts)
402     = return (NewHscRecomp False, iface, details)
403
404 -- Generate code and return both the new ModIface and the ModDetails.
405 hscCodeGenMake :: CodeGen (ModIface, ModDetails, CgGuts) (HscStatus, ModIface, ModDetails)
406 hscCodeGenMake hsc_env mod_summary (iface, details, cgguts)
407     = do hasStub <- hscCodeGenCompile hsc_env mod_summary cgguts
408          return (NewHscRecomp hasStub, iface, details)
409
410 -- Here we don't need the ModIface and ModDetails anymore.
411 hscCodeGenOneShot :: CodeGen (ModIface, ModDetails, CgGuts) HscStatus
412 hscCodeGenOneShot hsc_env mod_summary (_, _, cgguts)
413     = do hasStub <- hscCodeGenCompile hsc_env mod_summary cgguts
414          return (NewHscRecomp hasStub)
415
416 hscCodeGenCompile :: CodeGen CgGuts Bool
417 hscCodeGenCompile hsc_env mod_summary cgguts
418     = do let CgGuts{ -- This is the last use of the ModGuts in a compilation.
419                      -- From now on, we just use the bits we need.
420                      cg_module   = this_mod,
421                      cg_binds    = core_binds,
422                      cg_tycons   = tycons,
423                      cg_dir_imps = dir_imps,
424                      cg_foreign  = foreign_stubs,
425                      cg_home_mods = home_mods,
426                      cg_dep_pkgs = dependencies } = cgguts
427              dflags = hsc_dflags hsc_env
428              location = ms_location mod_summary
429              modName = ms_mod mod_summary
430              data_tycons = filter isDataTyCon tycons
431              -- cg_tycons includes newtypes, for the benefit of External Core,
432              -- but we don't generate any code for newtypes
433
434          -------------------
435          -- PREPARE FOR CODE GENERATION
436          -- Do saturation and convert to A-normal form
437          prepd_binds <- {-# SCC "CorePrep" #-}
438                         corePrepPgm dflags core_binds data_tycons ;
439          -----------------  Convert to STG ------------------
440          (stg_binds, cost_centre_info)
441              <- {-# SCC "CoreToStg" #-}
442                 myCoreToStg dflags home_mods this_mod prepd_binds       
443          ------------------  Code generation ------------------
444          abstractC <- {-# SCC "CodeGen" #-}
445                       codeGen dflags home_mods this_mod data_tycons
446                               foreign_stubs dir_imps cost_centre_info
447                               stg_binds
448          ------------------  Code output -----------------------
449          (stub_h_exists,stub_c_exists)
450              <- codeOutput dflags this_mod location foreign_stubs 
451                 dependencies abstractC
452          return stub_c_exists
453
454 hscCodeGenIdentity :: CodeGen a a
455 hscCodeGenIdentity hsc_env mod_summary a = return a
456
457 hscCodeGenSimple :: (a -> b) -> CodeGen a b
458 hscCodeGenSimple fn hsc_env mod_summary a = return (fn a)
459
460 hscCodeGenConst :: b -> CodeGen a b
461 hscCodeGenConst b hsc_env mod_summary a = return b
462
463 hscCodeGenInteractive :: CodeGen (ModIface, ModDetails, CgGuts)
464                                  (InteractiveStatus, ModIface, ModDetails)
465 hscCodeGenInteractive hsc_env mod_summary (iface, details, cgguts)
466 #ifdef GHCI
467     = do let CgGuts{ -- This is the last use of the ModGuts in a compilation.
468                      -- From now on, we just use the bits we need.
469                      cg_module   = this_mod,
470                      cg_binds    = core_binds,
471                      cg_tycons   = tycons,
472                      cg_foreign  = foreign_stubs,
473                      cg_home_mods = home_mods,
474                      cg_dep_pkgs = dependencies } = cgguts
475              dflags = hsc_dflags hsc_env
476              location = ms_location mod_summary
477              modName = ms_mod mod_summary
478              data_tycons = filter isDataTyCon tycons
479              -- cg_tycons includes newtypes, for the benefit of External Core,
480              -- but we don't generate any code for newtypes
481
482          -------------------
483          -- PREPARE FOR CODE GENERATION
484          -- Do saturation and convert to A-normal form
485          prepd_binds <- {-# SCC "CorePrep" #-}
486                         corePrepPgm dflags core_binds data_tycons ;
487          -----------------  Generate byte code ------------------
488          comp_bc <- byteCodeGen dflags prepd_binds data_tycons
489          ------------------ Create f-x-dynamic C-side stuff ---
490          (istub_h_exists, istub_c_exists) 
491              <- outputForeignStubs dflags this_mod location foreign_stubs
492          return (InteractiveRecomp istub_c_exists comp_bc, iface, details)
493 #else
494     = panic "GHC not compiled with interpreter"
495 #endif
496
497
498
499 --------------------------------------------------------------
500 -- Exterimental code end.
501 --------------------------------------------------------------
502
503         -- no errors or warnings; the individual passes
504         -- (parse/rename/typecheck) print messages themselves
505
506 hscMain
507   :: HscEnv
508   -> ModSummary
509   -> Bool               -- True <=> source unchanged
510   -> Bool               -- True <=> have an object file (for msgs only)
511   -> Maybe ModIface     -- Old interface, if available
512   -> Maybe (Int, Int)   -- Just (i,n) <=> module i of n (for msgs)
513   -> IO HscResult
514
515 hscMain hsc_env mod_summary
516         source_unchanged have_object maybe_old_iface
517         mb_mod_index
518  = do {
519       (recomp_reqd, maybe_checked_iface) <- 
520                 {-# SCC "checkOldIface" #-}
521                 checkOldIface hsc_env mod_summary 
522                               source_unchanged maybe_old_iface;
523
524       let no_old_iface = not (isJust maybe_checked_iface)
525           what_next | recomp_reqd || no_old_iface = hscRecomp 
526                     | otherwise                   = hscNoRecomp
527
528       ; what_next hsc_env mod_summary have_object 
529                   maybe_checked_iface
530                   mb_mod_index
531       }
532
533
534 ------------------------------
535 hscNoRecomp hsc_env mod_summary 
536             have_object (Just old_iface)
537             mb_mod_index
538  | isOneShot (ghcMode (hsc_dflags hsc_env))
539  = do {
540       compilationProgressMsg (hsc_dflags hsc_env) $
541         "compilation IS NOT required";
542       dumpIfaceStats hsc_env ;
543
544       let { bomb = panic "hscNoRecomp:OneShot" };
545       return (HscNoRecomp bomb bomb)
546       }
547  | otherwise
548  = do   { compilationProgressMsg (hsc_dflags hsc_env) $
549                 (showModuleIndex mb_mod_index ++ 
550                  "Skipping  " ++ showModMsg have_object mod_summary)
551
552         ; new_details <- {-# SCC "tcRnIface" #-}
553                          initIfaceCheck hsc_env $
554                          typecheckIface old_iface ;
555         ; dumpIfaceStats hsc_env
556
557         ; return (HscNoRecomp new_details old_iface)
558     }
559
560 hscNoRecomp hsc_env mod_summary 
561             have_object Nothing
562             mb_mod_index
563   = panic "hscNoRecomp" -- hscNoRecomp definitely expects to 
564                         -- have the old interface available
565
566 ------------------------------
567 hscRecomp hsc_env mod_summary
568           have_object maybe_old_iface
569           mb_mod_index
570  = case ms_hsc_src mod_summary of
571      HsSrcFile -> do
572         front_res <- hscFileFrontEnd hsc_env mod_summary mb_mod_index
573         case ghcMode (hsc_dflags hsc_env) of
574           JustTypecheck -> hscBootBackEnd hsc_env mod_summary maybe_old_iface front_res
575           _             -> hscBackEnd     hsc_env mod_summary maybe_old_iface front_res
576
577      HsBootFile -> do
578         front_res <- hscFileFrontEnd hsc_env mod_summary mb_mod_index
579         hscBootBackEnd hsc_env mod_summary maybe_old_iface front_res
580
581      ExtCoreFile -> do
582         front_res <- hscCoreFrontEnd hsc_env mod_summary mb_mod_index
583         hscBackEnd hsc_env mod_summary maybe_old_iface front_res
584
585 hscCoreFrontEnd hsc_env mod_summary mb_mod_index = do {
586             -------------------
587             -- PARSE
588             -------------------
589         ; inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
590         ; case parseCore inp 1 of
591             FailP s        -> errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-}) >> return Nothing
592             OkP rdr_module -> do {
593     
594             -------------------
595             -- RENAME and TYPECHECK
596             -------------------
597         ; (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
598                               tcRnExtCore hsc_env rdr_module
599         ; printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
600         ; case maybe_tc_result of
601              Nothing       -> return Nothing
602              Just mod_guts -> return (Just mod_guts)    -- No desugaring to do!
603         }}
604          
605
606 hscFileFrontEnd hsc_env mod_summary mb_mod_index = do {
607             -------------------
608             -- DISPLAY PROGRESS MESSAGE
609             -------------------
610         ; let dflags    = hsc_dflags hsc_env
611               one_shot  = isOneShot (ghcMode dflags)
612               toInterp  = hscTarget dflags == HscInterpreted
613         ; when (not one_shot) $
614                  compilationProgressMsg dflags $
615                  (showModuleIndex mb_mod_index ++
616                   "Compiling " ++ showModMsg (not toInterp) mod_summary)
617                         
618             -------------------
619             -- PARSE
620             -------------------
621         ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
622               hspp_buf  = ms_hspp_buf  mod_summary
623
624         ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
625
626         ; case maybe_parsed of {
627              Left err -> do { printBagOfErrors dflags (unitBag err)
628                             ; return Nothing } ;
629              Right rdr_module -> do {
630
631             -------------------
632             -- RENAME and TYPECHECK
633             -------------------
634           (tc_msgs, maybe_tc_result) 
635                 <- {-# SCC "Typecheck-Rename" #-}
636                    tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
637
638         ; printErrorsAndWarnings dflags tc_msgs
639         ; case maybe_tc_result of {
640              Nothing -> return Nothing ;
641              Just tc_result -> do {
642
643             -------------------
644             -- DESUGAR
645             -------------------
646         ; (warns, maybe_ds_result) <- {-# SCC "DeSugar" #-}
647                              deSugar hsc_env tc_result
648         ; printBagOfWarnings dflags warns
649         ; return maybe_ds_result
650         }}}}}
651
652 ------------------------------
653
654 hscFileCheck :: HscEnv -> ModSummary -> IO HscResult
655 hscFileCheck hsc_env mod_summary = do {
656             -------------------
657             -- PARSE
658             -------------------
659         ; let dflags    = hsc_dflags hsc_env
660               hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
661               hspp_buf  = ms_hspp_buf  mod_summary
662
663         ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
664
665         ; case maybe_parsed of {
666              Left err -> do { printBagOfErrors dflags (unitBag err)
667                             ; return HscFail } ;
668              Right rdr_module -> do {
669
670             -------------------
671             -- RENAME and TYPECHECK
672             -------------------
673           (tc_msgs, maybe_tc_result) 
674                 <- _scc_ "Typecheck-Rename" 
675                    tcRnModule hsc_env (ms_hsc_src mod_summary) 
676                         True{-save renamed syntax-}
677                         rdr_module
678
679         ; printErrorsAndWarnings dflags tc_msgs
680         ; case maybe_tc_result of {
681              Nothing -> return (HscChecked rdr_module Nothing Nothing);
682              Just tc_result -> do
683                 let md = ModDetails { 
684                                 md_types   = tcg_type_env tc_result,
685                                 md_exports = tcg_exports  tc_result,
686                                 md_insts   = tcg_insts    tc_result,
687                                 md_rules   = [panic "no rules"] }
688                                    -- Rules are CoreRules, not the
689                                    -- RuleDecls we get out of the typechecker
690                     rnInfo = do decl <- tcg_rn_decls tc_result
691                                 imports <- tcg_rn_imports tc_result
692                                 let exports = tcg_rn_exports tc_result
693                                 return (decl,imports,exports)
694                 return (HscChecked rdr_module 
695                                    rnInfo
696                                    (Just (tcg_binds tc_result,
697                                           tcg_rdr_env tc_result,
698                                           md)))
699         }}}}
700
701 ------------------------------
702 hscBootBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
703 -- For hs-boot files, there's no code generation to do
704
705 hscBootBackEnd hsc_env mod_summary maybe_old_iface Nothing 
706   = return HscFail
707 hscBootBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result)
708   = do  { details <- mkBootModDetails hsc_env ds_result
709
710         ; (new_iface, no_change) 
711                 <- {-# SCC "MkFinalIface" #-}
712                    mkIface hsc_env maybe_old_iface ds_result details
713
714         ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
715
716           -- And the answer is ...
717         ; dumpIfaceStats hsc_env
718
719         ; return (HscRecomp details new_iface
720                             False False Nothing)
721         }
722
723 ------------------------------
724 hscBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
725
726 hscBackEnd hsc_env mod_summary maybe_old_iface Nothing 
727   = return HscFail
728
729 hscBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result) 
730   = do  {       -- OMITTED: 
731                 -- ; seqList imported_modules (return ())
732
733           let one_shot  = isOneShot (ghcMode dflags)
734               dflags    = hsc_dflags hsc_env
735
736             -------------------
737             -- FLATTENING
738             -------------------
739         ; flat_result <- {-# SCC "Flattening" #-}
740                          flatten hsc_env ds_result
741
742
743 {-      TEMP: need to review space-leak fixing here
744         NB: even the code generator can force one of the
745             thunks for constructor arguments, for newtypes in particular
746
747         ; let   -- Rule-base accumulated from imported packages
748              pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
749
750                 -- In one-shot mode, ZAP the external package state at
751                 -- this point, because we aren't going to need it from
752                 -- now on.  We keep the name cache, however, because
753                 -- tidyCore needs it.
754              pcs_middle 
755                  | one_shot  = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
756                  | otherwise = pcs_tc
757
758         ; pkg_rule_base `seq` pcs_middle `seq` return ()
759 -}
760
761         -- alive at this point:  
762         --      pcs_middle
763         --      flat_result
764         --      pkg_rule_base
765
766             -------------------
767             -- SIMPLIFY
768             -------------------
769         ; simpl_result <- {-# SCC "Core2Core" #-}
770                           core2core hsc_env flat_result
771
772             -------------------
773             -- TIDY
774             -------------------
775         ; (cg_guts, details) <- {-# SCC "CoreTidy" #-}
776                                  tidyProgram hsc_env simpl_result
777
778         -- Alive at this point:  
779         --      tidy_result, pcs_final
780         --      hsc_env
781
782             -------------------
783             -- BUILD THE NEW ModIface and ModDetails
784             --  and emit external core if necessary
785             -- This has to happen *after* code gen so that the back-end
786             -- info has been set.  Not yet clear if it matters waiting
787             -- until after code output
788         ; (new_iface, no_change)
789                 <- {-# SCC "MkFinalIface" #-}
790                    mkIface hsc_env maybe_old_iface simpl_result details
791
792         ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
793
794             -- Space leak reduction: throw away the new interface if
795             -- we're in one-shot mode; we won't be needing it any
796             -- more.
797         ; final_iface <- if one_shot then return (error "no final iface")
798                          else return new_iface
799
800             -- Build the final ModDetails (except in one-shot mode, where
801             -- we won't need this information after compilation).
802         ; final_details <- if one_shot then return (error "no final details")
803                            else return $! details
804
805         -- Emit external core
806         ; emitExternalCore dflags cg_guts
807
808             -------------------
809             -- CONVERT TO STG and COMPLETE CODE GENERATION
810         ; (stub_h_exists, stub_c_exists, maybe_bcos)
811                 <- hscCodeGen dflags (ms_location mod_summary) cg_guts
812
813           -- And the answer is ...
814         ; dumpIfaceStats hsc_env
815
816         ; return (HscRecomp final_details
817                             final_iface
818                             stub_h_exists stub_c_exists
819                             maybe_bcos)
820          }
821
822
823
824 hscCodeGen dflags location
825     CgGuts{  -- This is the last use of the ModGuts in a compilation.
826               -- From now on, we just use the bits we need.
827         cg_module   = this_mod,
828         cg_binds    = core_binds,
829         cg_tycons   = tycons,
830         cg_dir_imps = dir_imps,
831         cg_foreign  = foreign_stubs,
832         cg_home_mods = home_mods,
833         cg_dep_pkgs = dependencies     }  = do {
834
835   let { data_tycons = filter isDataTyCon tycons } ;
836         -- cg_tycons includes newtypes, for the benefit of External Core,
837         -- but we don't generate any code for newtypes
838
839             -------------------
840             -- PREPARE FOR CODE GENERATION
841             -- Do saturation and convert to A-normal form
842   prepd_binds <- {-# SCC "CorePrep" #-}
843                  corePrepPgm dflags core_binds data_tycons ;
844
845   case hscTarget dflags of
846       HscNothing -> return (False, False, Nothing)
847
848       HscInterpreted ->
849 #ifdef GHCI
850         do  -----------------  Generate byte code ------------------
851             comp_bc <- byteCodeGen dflags prepd_binds data_tycons
852         
853             ------------------ Create f-x-dynamic C-side stuff ---
854             (istub_h_exists, istub_c_exists) 
855                <- outputForeignStubs dflags this_mod location foreign_stubs
856             
857             return ( istub_h_exists, istub_c_exists, Just comp_bc )
858 #else
859         panic "GHC not compiled with interpreter"
860 #endif
861
862       other ->
863         do
864             -----------------  Convert to STG ------------------
865             (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-}
866                          myCoreToStg dflags home_mods this_mod prepd_binds      
867
868             ------------------  Code generation ------------------
869             abstractC <- {-# SCC "CodeGen" #-}
870                          codeGen dflags home_mods this_mod data_tycons
871                                  foreign_stubs dir_imps cost_centre_info
872                                  stg_binds
873
874             ------------------  Code output -----------------------
875             (stub_h_exists, stub_c_exists)
876                      <- codeOutput dflags this_mod location foreign_stubs 
877                                 dependencies abstractC
878
879             return (stub_h_exists, stub_c_exists, Nothing)
880    }
881
882
883 hscCmmFile :: DynFlags -> FilePath -> IO Bool
884 hscCmmFile dflags filename = do
885   maybe_cmm <- parseCmmFile dflags (mkHomeModules []) filename
886   case maybe_cmm of
887     Nothing -> return False
888     Just cmm -> do
889         codeOutput dflags no_mod no_loc NoStubs [] [cmm]
890         return True
891   where
892         no_mod = panic "hscCmmFile: no_mod"
893         no_loc = ModLocation{ ml_hs_file  = Just filename,
894                               ml_hi_file  = panic "hscCmmFile: no hi file",
895                               ml_obj_file = panic "hscCmmFile: no obj file" }
896
897
898 myParseModule dflags src_filename maybe_src_buf
899  =    --------------------------  Parser  ----------------
900       showPass dflags "Parser" >>
901       {-# SCC "Parser" #-} do
902
903         -- sometimes we already have the buffer in memory, perhaps
904         -- because we needed to parse the imports out of it, or get the 
905         -- module name.
906       buf <- case maybe_src_buf of
907                 Just b  -> return b
908                 Nothing -> hGetStringBuffer src_filename
909
910       let loc  = mkSrcLoc (mkFastString src_filename) 1 0
911
912       case unP parseModule (mkPState buf loc dflags) of {
913
914         PFailed span err -> return (Left (mkPlainErrMsg span err));
915
916         POk _ rdr_module -> do {
917
918       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
919       
920       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
921                            (ppSourceStats False rdr_module) ;
922       
923       return (Right rdr_module)
924         -- ToDo: free the string buffer later.
925       }}
926
927
928 myCoreToStg dflags home_mods this_mod prepd_binds
929  = do 
930       stg_binds <- {-# SCC "Core2Stg" #-}
931              coreToStg home_mods prepd_binds
932
933       (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
934              stg2stg dflags home_mods this_mod stg_binds
935
936       return (stg_binds2, cost_centre_info)
937 \end{code}
938
939
940 %************************************************************************
941 %*                                                                      *
942 \subsection{Compiling a do-statement}
943 %*                                                                      *
944 %************************************************************************
945
946 When the UnlinkedBCOExpr is linked you get an HValue of type
947         IO [HValue]
948 When you run it you get a list of HValues that should be 
949 the same length as the list of names; add them to the ClosureEnv.
950
951 A naked expression returns a singleton Name [it].
952
953         What you type                   The IO [HValue] that hscStmt returns
954         -------------                   ------------------------------------
955         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
956                                         bindings: [x,y,...]
957
958         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
959                                         bindings: [x,y,...]
960
961         expr (of IO type)       ==>     expr >>= \ v -> return [v]
962           [NB: result not printed]      bindings: [it]
963           
964
965         expr (of non-IO type, 
966           result showable)      ==>     let v = expr in print v >> return [v]
967                                         bindings: [it]
968
969         expr (of non-IO type, 
970           result not showable)  ==>     error
971
972 \begin{code}
973 #ifdef GHCI
974 hscStmt         -- Compile a stmt all the way to an HValue, but don't run it
975   :: HscEnv
976   -> String                     -- The statement
977   -> IO (Maybe (HscEnv, [Name], HValue))
978
979 hscStmt hsc_env stmt
980   = do  { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
981         ; case maybe_stmt of {
982              Nothing      -> return Nothing ;   -- Parse error
983              Just Nothing -> return Nothing ;   -- Empty line
984              Just (Just parsed_stmt) -> do {    -- The real stuff
985
986                 -- Rename and typecheck it
987           let icontext = hsc_IC hsc_env
988         ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
989
990         ; case maybe_tc_result of {
991                 Nothing -> return Nothing ;
992                 Just (new_ic, bound_names, tc_expr) -> do {
993
994                 -- Then desugar, code gen, and link it
995         ; hval <- compileExpr hsc_env iNTERACTIVE 
996                               (ic_rn_gbl_env new_ic) 
997                               (ic_type_env new_ic)
998                               tc_expr
999
1000         ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
1001         }}}}}
1002
1003 hscTcExpr       -- Typecheck an expression (but don't run it)
1004   :: HscEnv
1005   -> String                     -- The expression
1006   -> IO (Maybe Type)
1007
1008 hscTcExpr hsc_env expr
1009   = do  { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
1010         ; let icontext = hsc_IC hsc_env
1011         ; case maybe_stmt of {
1012              Nothing      -> return Nothing ;   -- Parse error
1013              Just (Just (L _ (ExprStmt expr _ _)))
1014                         -> tcRnExpr hsc_env icontext expr ;
1015              Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
1016                                 return Nothing } ;
1017              } }
1018
1019 hscKcType       -- Find the kind of a type
1020   :: HscEnv
1021   -> String                     -- The type
1022   -> IO (Maybe Kind)
1023
1024 hscKcType hsc_env str
1025   = do  { maybe_type <- hscParseType (hsc_dflags hsc_env) str
1026         ; let icontext = hsc_IC hsc_env
1027         ; case maybe_type of {
1028              Just ty    -> tcRnType hsc_env icontext ty ;
1029              Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an type:" <+> quotes (text str)) ;
1030                                 return Nothing } ;
1031              Nothing    -> return Nothing } }
1032 #endif
1033 \end{code}
1034
1035 \begin{code}
1036 #ifdef GHCI
1037 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
1038 hscParseStmt = hscParseThing parseStmt
1039
1040 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
1041 hscParseType = hscParseThing parseType
1042 #endif
1043
1044 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
1045 hscParseIdentifier = hscParseThing parseIdentifier
1046
1047 hscParseThing :: Outputable thing
1048               => Lexer.P thing
1049               -> DynFlags -> String
1050               -> IO (Maybe thing)
1051         -- Nothing => Parse error (message already printed)
1052         -- Just x  => success
1053 hscParseThing parser dflags str
1054  = showPass dflags "Parser" >>
1055       {-# SCC "Parser" #-} do
1056
1057       buf <- stringToStringBuffer str
1058
1059       let loc  = mkSrcLoc FSLIT("<interactive>") 1 0
1060
1061       case unP parser (mkPState buf loc dflags) of {
1062
1063         PFailed span err -> do { printError span err;
1064                                  return Nothing };
1065
1066         POk _ thing -> do {
1067
1068       --ToDo: can't free the string buffer until we've finished this
1069       -- compilation sweep and all the identifiers have gone away.
1070       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
1071       return (Just thing)
1072       }}
1073 \end{code}
1074
1075 %************************************************************************
1076 %*                                                                      *
1077         Desugar, simplify, convert to bytecode, and link an expression
1078 %*                                                                      *
1079 %************************************************************************
1080
1081 \begin{code}
1082 #ifdef GHCI
1083 compileExpr :: HscEnv 
1084             -> Module -> GlobalRdrEnv -> TypeEnv
1085             -> LHsExpr Id
1086             -> IO HValue
1087
1088 compileExpr hsc_env this_mod rdr_env type_env tc_expr
1089   = do  { let { dflags  = hsc_dflags hsc_env ;
1090                 lint_on = dopt Opt_DoCoreLinting dflags }
1091               
1092                 -- Desugar it
1093         ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
1094         
1095                 -- Flatten it
1096         ; flat_expr <- flattenExpr hsc_env ds_expr
1097
1098                 -- Simplify it
1099         ; simpl_expr <- simplifyExpr dflags flat_expr
1100
1101                 -- Tidy it (temporary, until coreSat does cloning)
1102         ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
1103
1104                 -- Prepare for codegen
1105         ; prepd_expr <- corePrepExpr dflags tidy_expr
1106
1107                 -- Lint if necessary
1108                 -- ToDo: improve SrcLoc
1109         ; if lint_on then 
1110                 case lintUnfolding noSrcLoc [] prepd_expr of
1111                    Just err -> pprPanic "compileExpr" err
1112                    Nothing  -> return ()
1113           else
1114                 return ()
1115
1116                 -- Convert to BCOs
1117         ; bcos <- coreExprToBCOs dflags prepd_expr
1118
1119                 -- link it
1120         ; hval <- linkExpr hsc_env bcos
1121
1122         ; return hval
1123      }
1124 #endif
1125 \end{code}
1126
1127
1128 %************************************************************************
1129 %*                                                                      *
1130         Statistics on reading interfaces
1131 %*                                                                      *
1132 %************************************************************************
1133
1134 \begin{code}
1135 dumpIfaceStats :: HscEnv -> IO ()
1136 dumpIfaceStats hsc_env
1137   = do  { eps <- readIORef (hsc_EPS hsc_env)
1138         ; dumpIfSet (dump_if_trace || dump_rn_stats)
1139                     "Interface statistics"
1140                     (ifaceStats eps) }
1141   where
1142     dflags = hsc_dflags hsc_env
1143     dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
1144     dump_if_trace = dopt Opt_D_dump_if_trace dflags
1145 \end{code}
1146
1147 %************************************************************************
1148 %*                                                                      *
1149         Progress Messages: Module i of n
1150 %*                                                                      *
1151 %************************************************************************
1152
1153 \begin{code}
1154 showModuleIndex Nothing = ""
1155 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1156     where
1157         n_str = show n
1158         i_str = show i
1159         padded = replicate (length n_str - length i_str) ' ' ++ i_str
1160 \end{code}
1161