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