[project @ 2001-03-13 12:50:29 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / HscMain.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
3 %
4 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
5
6 \begin{code}
7 module HscMain ( HscResult(..), hscMain, 
8 #ifdef GHCI
9                  hscStmt,
10 #endif
11                  initPersistentCompilerState ) where
12
13 #include "HsVersions.h"
14
15 #ifdef GHCI
16 import RdrHsSyn         ( RdrNameStmt )
17 import Rename           ( renameStmt )
18 import ByteCodeGen      ( byteCodeGen )
19 import Id               ( Id, idName, setGlobalIdDetails )
20 import IdInfo           ( GlobalIdDetails(VanillaGlobal) )
21 import HscTypes         ( InteractiveContext(..), TyThing(..) )
22 import PrelNames        ( iINTERACTIVE )
23 import CoreTidy         ( tidyCoreExpr )
24 import StringBuffer     ( stringToStringBuffer )
25 #endif
26
27 import HsSyn
28
29 import Id               ( idName )
30 import IdInfo           ( CafInfo(..), CgInfoEnv, CgInfo(..) )
31 import StringBuffer     ( hGetStringBuffer, freeStringBuffer )
32 import Parser
33 import Lex              ( PState(..), ParseResult(..) )
34 import SrcLoc           ( mkSrcLoc )
35 import Rename           ( checkOldIface, renameModule, closeIfaceDecls )
36 import Rules            ( emptyRuleBase )
37 import PrelInfo         ( wiredInThingEnv, wiredInThings )
38 import PrelNames        ( vanillaSyntaxMap, knownKeyNames )
39 import MkIface          ( completeIface, writeIface, pprIface )
40 import TcModule
41 import InstEnv          ( emptyInstEnv )
42 import Desugar
43 import SimplCore
44 import CoreUtils        ( coreBindsSize )
45 import CoreTidy         ( tidyCorePgm )
46 import CorePrep         ( corePrepPgm )
47 import StgSyn
48 import CoreToStg        ( coreToStg )
49 import SimplStg         ( stg2stg )
50 import CodeGen          ( codeGen )
51 import CodeOutput       ( codeOutput )
52
53 import Module           ( ModuleName, moduleName, mkHomeModule, 
54                           moduleUserString )
55 import CmdLineOpts
56 import ErrUtils         ( dumpIfSet_dyn, showPass, printError )
57 import Util             ( unJust )
58 import UniqSupply       ( mkSplitUniqSupply )
59
60 import Bag              ( emptyBag )
61 import Outputable
62 import Interpreter
63 import CmStaticInfo     ( GhciMode(..) )
64 import HscStats         ( ppSourceStats )
65 import HscTypes
66 import FiniteMap        ( FiniteMap, plusFM, emptyFM, addToFM )
67 import OccName          ( OccName )
68 import Name             ( Name, nameModule, nameOccName, getName, isGlobalName )
69 import NameEnv          ( emptyNameEnv, mkNameEnv )
70 import Module           ( Module, lookupModuleEnvByName )
71 import Maybes           ( orElse )
72
73 import IOExts           ( newIORef, readIORef, writeIORef, unsafePerformIO )
74
75 import Monad            ( when )
76 import Maybe            ( isJust )
77 import IO
78 \end{code}
79
80
81 %************************************************************************
82 %*                                                                      *
83 \subsection{The main compiler pipeline}
84 %*                                                                      *
85 %************************************************************************
86
87 \begin{code}
88 data HscResult
89    -- compilation failed
90    = HscFail     PersistentCompilerState -- updated PCS
91    -- concluded that it wasn't necessary
92    | HscNoRecomp PersistentCompilerState -- updated PCS
93                  ModDetails              -- new details (HomeSymbolTable additions)
94                  ModIface                -- new iface (if any compilation was done)
95    -- did recompilation
96    | HscRecomp   PersistentCompilerState -- updated PCS
97                  ModDetails              -- new details (HomeSymbolTable additions)
98                  ModIface                -- new iface (if any compilation was done)
99                  (Maybe String)          -- generated stub_h filename (in TMPDIR)
100                  (Maybe String)          -- generated stub_c filename (in TMPDIR)
101                  (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
102              
103
104         -- no errors or warnings; the individual passes
105         -- (parse/rename/typecheck) print messages themselves
106
107 hscMain
108   :: GhciMode
109   -> DynFlags
110   -> Module
111   -> ModuleLocation             -- location info
112   -> Bool                       -- source unchanged?
113   -> Maybe ModIface             -- old interface, if available
114   -> HomeSymbolTable            -- for home module ModDetails
115   -> HomeIfaceTable
116   -> PersistentCompilerState    -- IN: persistent compiler state
117   -> IO HscResult
118
119 hscMain ghci_mode dflags mod location source_unchanged maybe_old_iface hst hit pcs
120  = do {
121       showPass dflags ("Checking old interface for hs = " 
122                         ++ show (ml_hs_file location)
123                         ++ ", hspp = " ++ show (ml_hspp_file location));
124
125       (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
126          <- checkOldIface ghci_mode dflags hit hst pcs 
127                 (unJust "hscMain" (ml_hi_file location))
128                 source_unchanged maybe_old_iface;
129
130       if errs_found then
131          return (HscFail pcs_ch)
132       else do {
133
134       let no_old_iface = not (isJust maybe_checked_iface)
135           what_next | recomp_reqd || no_old_iface = hscRecomp 
136                     | otherwise                   = hscNoRecomp
137       ;
138       what_next ghci_mode dflags mod location maybe_checked_iface
139                 hst hit pcs_ch
140       }}
141
142
143 -- we definitely expect to have the old interface available
144 hscNoRecomp ghci_mode dflags mod location (Just old_iface) hst hit pcs_ch
145  | ghci_mode == OneShot
146  = do {
147       hPutStrLn stderr "compilation IS NOT required";
148       let { bomb = panic "hscNoRecomp:OneShot" };
149       return (HscNoRecomp pcs_ch bomb bomb)
150       }
151  | otherwise
152  = do {
153       when (verbosity dflags >= 1) $
154                 hPutStrLn stderr ("Skipping  " ++ compMsg mod location);
155
156       -- CLOSURE
157       (pcs_cl, closure_errs, cl_hs_decls) 
158          <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
159       if closure_errs then 
160          return (HscFail pcs_cl) 
161       else do {
162
163       -- TYPECHECK
164       maybe_tc_result 
165         <- typecheckIface dflags pcs_cl hst old_iface (vanillaSyntaxMap, cl_hs_decls);
166
167       case maybe_tc_result of {
168          Nothing -> return (HscFail pcs_cl);
169          Just (pcs_tc, new_details) ->
170
171       return (HscNoRecomp pcs_tc new_details old_iface)
172       }}}
173
174 compMsg mod location =
175     mod_str ++ take (12 - length mod_str) (repeat ' ')
176     ++ " (" ++ unJust "hscRecomp" (ml_hs_file location) ++ ")"
177  where mod_str = moduleUserString mod
178
179
180 hscRecomp ghci_mode dflags mod location maybe_checked_iface hst hit pcs_ch
181  = do   {
182         ; when (verbosity dflags >= 1) $
183                 hPutStrLn stderr ("Compiling " ++ compMsg mod location);
184
185           -- what target are we shooting for?
186         ; let toInterp = dopt_HscLang dflags == HscInterpreted
187
188             -------------------
189             -- PARSE
190             -------------------
191         ; maybe_parsed <- myParseModule dflags 
192                              (unJust "hscRecomp:hspp" (ml_hspp_file location))
193         ; case maybe_parsed of {
194              Nothing -> return (HscFail pcs_ch);
195              Just rdr_module -> do {
196         ; let this_mod = mkHomeModule (hsModuleName rdr_module)
197     
198             -------------------
199             -- RENAME
200             -------------------
201         ; (pcs_rn, print_unqualified, maybe_rn_result) 
202              <- _scc_ "Rename" 
203                  renameModule dflags hit hst pcs_ch this_mod rdr_module
204         ; case maybe_rn_result of {
205              Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
206              Just (is_exported, new_iface, rn_hs_decls) -> do {
207     
208             -- In interactive mode, we don't want to discard any top-level entities at
209             -- all (eg. do not inline them away during simplification), and retain them
210             -- all in the TypeEnv so they are available from the command line.
211             --
212             -- isGlobalName separates the user-defined top-level names from those
213             -- introduced by the type checker.
214         ; let dont_discard | ghci_mode == Interactive = isGlobalName
215                            | otherwise = is_exported
216
217             -------------------
218             -- TYPECHECK
219             -------------------
220         ; maybe_tc_result 
221             <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface 
222                                              print_unqualified rn_hs_decls 
223         ; case maybe_tc_result of {
224              Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
225              Just (pcs_tc, tc_result) -> do {
226     
227             -------------------
228             -- DESUGAR
229             -------------------
230         ; (ds_details, foreign_stuff) 
231              <- _scc_ "DeSugar" 
232                 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
233
234             -------------------
235             -- SIMPLIFY
236             -------------------
237         ; simpl_details
238              <- _scc_     "Core2Core"
239                 core2core dflags pcs_tc hst dont_discard ds_details
240
241             -------------------
242             -- TIDY
243             -------------------
244         ; cg_info_ref <- newIORef Nothing ;
245         ; let cg_info :: CgInfoEnv
246               cg_info = unsafePerformIO $ do {
247                            maybe_cg_env <- readIORef cg_info_ref ;
248                            case maybe_cg_env of
249                              Just env -> return env
250                              Nothing  -> do { printError "Urk! Looked at CgInfo too early!";
251                                               return emptyNameEnv } }
252                 -- cg_info_ref will be filled in just after restOfCodeGeneration
253                 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
254
255         ; (pcs_simpl, tidy_details) 
256              <- tidyCorePgm dflags this_mod pcs_tc cg_info simpl_details
257       
258             -------------------
259             -- PREPARE FOR CODE GENERATION
260             -------------------
261               -- Do saturation and convert to A-normal form
262         ; prepd_details <- corePrepPgm dflags tidy_details
263
264             -------------------
265             -- CONVERT TO STG and COMPLETE CODE GENERATION
266             -------------------
267         ; let
268             ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
269
270             local_tycons     = typeEnvTyCons  env_tc
271             local_classes    = typeEnvClasses env_tc
272
273             imported_module_names = map ideclName (hsModuleImports rdr_module)
274             imported_modules = map mod_name_to_Module imported_module_names
275
276             (h_code,c_code,fe_binders) = foreign_stuff
277         
278             pit = pcs_PIT pcs_simpl
279
280             mod_name_to_Module :: ModuleName -> Module
281             mod_name_to_Module nm
282                = let str_mi = lookupModuleEnvByName hit nm `orElse`
283                               lookupModuleEnvByName pit nm `orElse`
284                               pprPanic "mod_name_to_Module: no hst or pst mapping for" 
285                                 (ppr nm)
286                  in  mi_module str_mi
287
288         ; (maybe_stub_h_filename, maybe_stub_c_filename,
289            maybe_bcos, final_iface )
290            <- if toInterp
291                 then do 
292                     -----------------  Generate byte code ------------------
293                     (bcos,itbl_env) <- byteCodeGen dflags binds 
294                                         local_tycons local_classes
295
296                     -- Fill in the code-gen info
297                     writeIORef cg_info_ref (Just emptyNameEnv)
298
299                     ------------------ BUILD THE NEW ModIface ------------
300                     final_iface <- _scc_ "MkFinalIface" 
301                           mkFinalIface ghci_mode dflags location 
302                                    maybe_checked_iface new_iface tidy_details
303
304                     return ( Nothing, Nothing, 
305                              Just (bcos,itbl_env), final_iface )
306
307                 else do
308                     -----------------  Convert to STG ------------------
309                     (stg_binds, cost_centre_info, stg_back_end_info) 
310                               <- _scc_ "CoreToStg"
311                                   myCoreToStg dflags this_mod binds
312                     
313                     -- Fill in the code-gen info for the earlier tidyCorePgm
314                     writeIORef cg_info_ref (Just stg_back_end_info)
315
316                     ------------------ BUILD THE NEW ModIface ------------
317                     final_iface <- _scc_ "MkFinalIface" 
318                           mkFinalIface ghci_mode dflags location 
319                                    maybe_checked_iface new_iface tidy_details
320
321                     ------------------  Code generation ------------------
322                     abstractC <- _scc_ "CodeGen"
323                                   codeGen dflags this_mod imported_modules
324                                          cost_centre_info fe_binders
325                                          local_tycons stg_binds
326                     
327                     ------------------  Code output -----------------------
328                     (maybe_stub_h_name, maybe_stub_c_name)
329                        <- codeOutput dflags this_mod local_tycons
330                              binds stg_binds
331                              c_code h_code abstractC
332                         
333                     return ( maybe_stub_h_name, maybe_stub_c_name, 
334                              Nothing, final_iface )
335
336         ; let final_details = tidy_details {md_binds = []} 
337
338
339           -- and the answer is ...
340         ; return (HscRecomp pcs_simpl
341                             final_details
342                             final_iface
343                             maybe_stub_h_filename maybe_stub_c_filename
344                             maybe_bcos)
345           }}}}}}}
346
347
348
349 mkFinalIface ghci_mode dflags location 
350         maybe_old_iface new_iface new_details
351  = case completeIface maybe_old_iface new_iface new_details of
352
353       (new_iface, Nothing) -- no change in the interfacfe
354          -> do when (dopt Opt_D_dump_hi_diffs dflags)
355                     (printDump (text "INTERFACE UNCHANGED"))
356                dumpIfSet_dyn dflags Opt_D_dump_hi
357                              "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
358                return new_iface
359
360       (new_iface, Just sdoc_diffs)
361          -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" 
362                                     sdoc_diffs
363                dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" 
364                                     (pprIface new_iface)
365
366                -- Write the interface file, if not in interactive mode
367                when (ghci_mode /= Interactive) 
368                     (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
369                                 new_iface)
370                return new_iface
371
372
373 myParseModule dflags src_filename
374  = do --------------------------  Parser  ----------------
375       showPass dflags "Parser"
376       _scc_  "Parser" do
377
378       buf <- hGetStringBuffer True{-expand tabs-} src_filename
379
380       let glaexts | dopt Opt_GlasgowExts dflags = 1#
381                   | otherwise                   = 0#
382
383       case parseModule buf PState{ bol = 0#, atbol = 1#,
384                                    context = [], glasgow_exts = glaexts,
385                                    loc = mkSrcLoc (_PK_ src_filename) 1 } of {
386
387         PFailed err -> do { hPutStrLn stderr (showSDoc err);
388                             freeStringBuffer buf;
389                             return Nothing };
390
391         POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
392
393       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
394       
395       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
396                            (ppSourceStats False rdr_module) ;
397       
398       return (Just rdr_module)
399         -- ToDo: free the string buffer later.
400       }}
401
402
403 myCoreToStg dflags this_mod tidy_binds
404  = do 
405       () <- coreBindsSize tidy_binds `seq` return ()
406       -- TEMP: the above call zaps some space usage allocated by the
407       -- simplifier, which for reasons I don't understand, persists
408       -- thoroughout code generation
409
410       stg_binds <- _scc_ "Core2Stg" coreToStg dflags tidy_binds
411
412       (stg_binds2, cost_centre_info)
413            <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
414
415       let env_rhs :: CgInfoEnv
416           env_rhs = mkNameEnv [ (idName bndr, CgInfo (stgRhsArity rhs) caf_info)
417                               | (bind,_) <- stg_binds2, 
418                                 let caf_info 
419                                      | stgBindHasCafRefs bind = MayHaveCafRefs
420                                      | otherwise = NoCafRefs,
421                                 (bndr,rhs) <- stgBindPairs bind ]
422
423       return (stg_binds2, cost_centre_info, env_rhs)
424    where
425       stgBindPairs (StgNonRec _ b r) = [(b,r)]
426       stgBindPairs (StgRec    _ prs) = prs
427 \end{code}
428
429
430 %************************************************************************
431 %*                                                                      *
432 \subsection{Compiling a do-statement}
433 %*                                                                      *
434 %************************************************************************
435
436 \begin{code}
437 #ifdef GHCI
438 hscStmt
439   :: DynFlags
440   -> HomeSymbolTable    
441   -> HomeIfaceTable
442   -> PersistentCompilerState    -- IN: persistent compiler state
443   -> InteractiveContext         -- Context for compiling
444   -> String                     -- The statement
445   -> Bool                       -- just treat it as an expression
446   -> IO ( PersistentCompilerState, 
447           Maybe ( [Id], 
448                   Type, 
449                   UnlinkedBCOExpr) )
450 \end{code}
451
452 When the UnlinkedBCOExpr is linked you get an HValue of type
453         IO [HValue]
454 When you run it you get a list of HValues that should be 
455 the same length as the list of names; add them to the ClosureEnv.
456
457 A naked expression returns a singleton Name [it].
458
459         What you type                   The IO [HValue] that hscStmt returns
460         -------------                   ------------------------------------
461         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
462                                         bindings: [x,y,...]
463
464         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
465                                         bindings: [x,y,...]
466
467         expr (of IO type)       ==>     expr >>= \ v -> return [v]
468           [NB: result not printed]      bindings: [it]
469           
470
471         expr (of non-IO type, 
472           result showable)      ==>     let v = expr in print v >> return [v]
473                                         bindings: [it]
474
475         expr (of non-IO type, 
476           result not showable)  ==>     error
477
478 \begin{code}
479 hscStmt dflags hst hit pcs0 icontext stmt just_expr
480    = let 
481         InteractiveContext { 
482              ic_rn_env   = rn_env, 
483              ic_type_env = type_env,
484              ic_module   = scope_mod } = icontext
485      in
486      do { maybe_stmt <- hscParseStmt dflags stmt
487         ; case maybe_stmt of
488              Nothing -> return (pcs0, Nothing)
489              Just parsed_stmt -> do {
490
491            let { notExprStmt (ExprStmt _ _) = False;
492                  notExprStmt _              = True 
493                };
494
495            if (just_expr && notExprStmt parsed_stmt)
496                 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
497                         return (pcs0, Nothing)
498                 else do {
499
500                 -- Rename it
501           (pcs1, print_unqual, maybe_renamed_stmt)
502                  <- renameStmt dflags hit hst pcs0 scope_mod 
503                                 iNTERACTIVE rn_env parsed_stmt
504
505         ; case maybe_renamed_stmt of
506                 Nothing -> return (pcs0, Nothing)
507                 Just (bound_names, rn_stmt) -> do {
508
509                 -- Typecheck it
510           maybe_tc_return <- 
511             if just_expr 
512                 then case rn_stmt of { (syn, ExprStmt e _, decls) -> 
513                      typecheckExpr dflags pcs1 hst type_env
514                            print_unqual iNTERACTIVE (syn,e,decls) }
515                 else typecheckStmt dflags pcs1 hst type_env
516                            print_unqual iNTERACTIVE bound_names rn_stmt
517
518         ; case maybe_tc_return of
519                 Nothing -> return (pcs0, Nothing)
520                 Just (pcs2, tc_expr, bound_ids, ty) ->  do {
521
522                 -- Desugar it
523           ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
524         
525                 -- Simplify it
526         ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
527
528                 -- Tidy it (temporary, until coreSat does cloning)
529         ; tidy_expr <- tidyCoreExpr simpl_expr
530
531                 -- Saturate it
532         ; sat_expr <- coreSatExpr dflags tidy_expr
533
534                 -- Convert to BCOs
535         ; bcos <- coreExprToBCOs dflags sat_expr
536
537         ; let
538                 -- Make all the bound ids "global" ids, now that
539                 -- they're notionally top-level bindings.  This is
540                 -- important: otherwise when we come to compile an expression
541                 -- using these ids later, the byte code generator will consider
542                 -- the occurrences to be free rather than global.
543              global_bound_ids = map globaliseId bound_ids;
544              globaliseId id   = setGlobalIdDetails id VanillaGlobal
545
546         ; return (pcs2, Just (global_bound_ids, ty, bcos))
547
548      }}}}}
549
550 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
551 hscParseStmt dflags str
552  = do --------------------------  Parser  ----------------
553       showPass dflags "Parser"
554       _scc_ "Parser" do
555
556       buf <- stringToStringBuffer str
557
558       let glaexts | dopt Opt_GlasgowExts dflags = 1#
559                   | otherwise                   = 0#
560
561       case parseStmt buf PState{ bol = 0#, atbol = 1#,
562                                  context = [], glasgow_exts = glaexts,
563                                  loc = mkSrcLoc SLIT("<no file>") 0 } of {
564
565         PFailed err -> do { hPutStrLn stderr (showSDoc err);
566 --      Not yet implemented in <4.11    freeStringBuffer buf;
567                             return Nothing };
568
569         -- no stmt: the line consisted of just space or comments
570         POk _ Nothing -> return Nothing;
571
572         POk _ (Just rdr_stmt) -> do {
573
574       --ToDo: can't free the string buffer until we've finished this
575       -- compilation sweep and all the identifiers have gone away.
576       --freeStringBuffer buf;
577       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
578       return (Just rdr_stmt)
579       }}
580 #endif
581 \end{code}
582
583 %************************************************************************
584 %*                                                                      *
585 \subsection{Initial persistent state}
586 %*                                                                      *
587 %************************************************************************
588
589 \begin{code}
590 initPersistentCompilerState :: IO PersistentCompilerState
591 initPersistentCompilerState 
592   = do prs <- initPersistentRenamerState
593        return (
594         PCS { pcs_PIT   = emptyIfaceTable,
595               pcs_PTE   = wiredInThingEnv,
596               pcs_insts = emptyInstEnv,
597               pcs_rules = emptyRuleBase,
598               pcs_PRS   = prs
599             }
600         )
601
602 initPersistentRenamerState :: IO PersistentRenamerState
603   = do us <- mkSplitUniqSupply 'r'
604        return (
605         PRS { prsOrig  = NameSupply { nsUniqs = us,
606                                       nsNames = initOrigNames,
607                                       nsIPs   = emptyFM },
608               prsDecls   = (emptyNameEnv, 0),
609               prsInsts   = (emptyBag, 0),
610               prsRules   = (emptyBag, 0),
611               prsImpMods = emptyFM
612             }
613         )
614
615 initOrigNames :: FiniteMap (ModuleName,OccName) Name
616 initOrigNames 
617    = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
618      where
619         grab names = foldl add emptyFM names
620         add env name 
621            = addToFM env (moduleName (nameModule name), nameOccName name) name
622
623
624 initRules :: PackageRuleBase
625 initRules = emptyRuleBase
626 {- SHOULD BE (ish)
627             foldl add emptyVarEnv builtinRules
628           where
629             add env (name,rule) 
630               = extendRuleBase env name rule
631 -}
632 \end{code}